Swift - 使用表格组件(UITableView)实现单列表
作者:hangge | 2015-01-21 09:40
(本文代码已升级至Swift4)

--- Controls.plist ---
源码下载:
hangge_552.zip
1,样例说明:
(1)列表内容从 Controls.plist 文件中读取,类型为 Array。
(2)点击列表项会弹出消息框显示该项信息。
(3)按住列表项向左滑动,会出现删除按钮。点击删除即可删除该项。
2,效果图

3,单元格复用机制:
由于普通的表格视图中对的单元格形式一般都是相同的,所以本例采用了单元格复用机制,可以大大提高程序性能。
实现方式是初始化创建 UITableView 实例时使用 .register(UITableViewCell.self, forCellReuseIdentifier: "SwiftCell") 创建一个可供重用的 UITableViewCell。并将其注册到UITableView,ID为 SwiftCell。
下次碰到形式(或结构)相同的单元就可以直接使用 UITableView 的 dequeueReusableCell 方法从UITableView中取出。
4,示例代码
--- ViewController.swift ---
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var ctrlnames:[String]?
var tableView:UITableView?
override func loadView() {
super.loadView()
}
override func viewDidLoad() {
super.viewDidLoad()
//初始化数据,这一次数据,我们放在属性列表文件里
self.ctrlnames = NSArray(contentsOfFile:
Bundle.main.path(forResource: "Controls", ofType:"plist")!) as? Array
print(self.ctrlnames)
//创建表视图
self.tableView = UITableView(frame: self.view.frame, style:.plain)
self.tableView!.delegate = self
self.tableView!.dataSource = self
//创建一个重用的单元格
self.tableView!.register(UITableViewCell.self,
forCellReuseIdentifier: "SwiftCell")
self.view.addSubview(self.tableView!)
//创建表头标签
let frame = CGRect(x:0, y:0, width:self.view.bounds.size.width, height:30)
let headerLabel = UILabel(frame: frame)
headerLabel.backgroundColor = UIColor.black
headerLabel.textColor = UIColor.white
headerLabel.numberOfLines = 0
headerLabel.lineBreakMode = .byWordWrapping
headerLabel.text = "常见 UIKit 控件"
headerLabel.font = UIFont.italicSystemFont(ofSize: 20)
self.tableView!.tableHeaderView = headerLabel
}
//在本例中,只有一个分区
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//返回表格行数(也就是返回控件数)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.ctrlnames!.count
}
//创建各单元显示内容(创建参数indexPath指定的单元)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
-> UITableViewCell {
//为了提供表格显示性能,已创建完成的单元需重复使用
let identify:String = "SwiftCell"
//同一形式的单元格重复使用,在声明时已注册
let cell = tableView.dequeueReusableCell(withIdentifier: identify,
for: indexPath)
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = self.ctrlnames![indexPath.row]
return cell
}
// UITableViewDelegate 方法,处理列表项的选中事件
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView!.deselectRow(at: indexPath, animated: true)
let itemString = self.ctrlnames![indexPath.row]
let alertController = UIAlertController(title: "提示!",
message: "你选中了【\(itemString)】", preferredStyle: .alert)
let okAction = UIAlertAction(title: "确定", style: .default,handler: nil)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
//滑动删除必须实现的方法
func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCellEditingStyle,
forRowAt indexPath: IndexPath) {
print("删除\(indexPath.row)")
let index = indexPath.row
self.ctrlnames?.remove(at: index)
self.tableView?.deleteRows(at: [indexPath],
with: .top)
}
//滑动删除
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath)
-> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.delete
}
//修改删除按钮的文字
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt
indexPath: IndexPath) -> String? {
return "删"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <string>标签 UILabel</string> <string>文本框 UITextField</string> <string>按钮 UIButton</string> <string>开关按钮 UISwitch</string> <string>分段控件 UISegmentControl</string> <string>图像 UIImageView</string> <string>进度条 UIProgressView</string> <string>滑动条 UISlider</string> <string>警告框 UIAlertView</string> </array> </plist>
源码下载:
全部评论(11)
航哥,每天都在跟着你学习,你分享的东西都是很实用的,谢谢
站长回复:很高兴你能喜欢我的文章。欢迎常来看看,我会一直更新下去的。
航哥,怎样删除,可以把plist中的元素也删了?
站长回复:文章中的删除只是把内存中的数据条目删除,原来plist数据还没变。你可以删除后再把最新的数据保存成plist。
航哥,像这种数组成员很少的变量,应该是定义一个public的全局变量好,还是用plist写一个array数组来调用比较好?根据你的经验来看?我个人认为手动写plist文件没有自定义变量来的快,呵呵!
站长回复:两个方法虽然都可以,但其实像是一些配置数据,还有全局使用的数据还是定义在plist文件中会更加规范些。
这个有没有原件,那个plist文件内容老是调不出来
站长回复:工程源码已上传,你可以看下。
把UITableViewDataSource 添加进去 ,会报错 :Type’ViewController’ does not conform to protocol'UITableViewDataSource'
站长回复:应该是你没有实现UITableViewDataSource协议的两个方法:
航哥看了你的tableView,然后自己写了一些关于自定义UITableViewCell的demo,然后航哥 self.tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: identify)这样注册以后在建立cell方法中这样写。
(identify 是 let identify:String = "cell")
let cell:TableViewCell = tableView.dequeueReusableCellWithIdentifier(identify, forIndexPath: indexPath) as! TableViewCell
但是一直关联不到我自己建立的那个cell上,请问下航哥在建立 继承uitabViewcell的cell的时候怎么关联呢??
站长回复:可以参考我这篇文章:http://www.hangge.com/blog/cache/detail_873.html
航哥能不能专门写一张讲解 as 和as? 还有anyobject的,感觉对于赋值强转 和OC 有点不明白
站长回复:AnyObject 代表任何class类型的对象实例。可以看我原来写的这篇文章:Swift - AnyObject与Any的区别(http://www.hangge.com/blog/cache/detail_694.html)
我后面会找时间写篇文章讲解as as?,你可以关注下。
按照作者的方法,我已经实现了。我有个问题,NSBundle.mainBundle().pathForResource("Controls", ofType:"plist")!) as? Array 这行的as?Array起什么作用呢?刚开始转Swift,多多指教,谢谢。
站长回复:NSArray是Objective-C里的数组类型。Array是Swift里的数组类型。
为了便于使用,这里把NSArray做了类型转换,转成Array。
as 关键字就是起到类型转换的作用。
谢谢航哥,航哥能否加下我的QQ 57223165,或者航哥你搞个QQ群起来吧!
还有些其他问题想咨询一下,现在ios swift网上资源太少了
搜索起来累西累呢~
站长回复:QQ暂时都只加家人或是身边朋友,所以不好意思啊。不过你可以通过网站的右上角给我留言,或者把问题整理下发我邮箱(yuhang0385@163.com)。我都会回复的。
原来是我定义问题
var ctrlnames:[String]? 和 var ctrlnames:NSArray
有啥区别呢?
站长回复:NSArray是Objective-C原来就有的类型,Array是Swift新增的类型,Array新加许多方法,更便于操作,所以Swift中可以使用Array的尽量使用Array。var ctrlnames:Array? 可以简写成 var ctrlnames:[String]?
NSBundle.mainBundle().pathForResource("Controls", ofType:"plist")!)
为什么我这边调试就是获取不到呢?
站长回复:参考我另一个回复