【www.bbyears.com--页面特效】
在StoryBoard中,我们可以很方便地设置表格(tableView)内部单元格(cell)样式。但如果多个页面的tableView单元格样式都一样的话,再一个个单独设置不仅麻烦,而且会造成代码冗余。
最好的办法就是把单元格提取出来做成自定义组件,从而实现cell的复用。
对于自定义单元格组件,我门既可以通过继承 UITableViewCell,使用纯代码来实现。也可以配合 XIB 来实现。前面一种方法我原来写过很多样例了,本文介绍后面一种方法。
1,使用xib制作tableView的cell介绍
同纯代码相比,xib实现自定义样式会方便很多。不管布局约束,还是样式的设置,使用xib都很简单。
下面通过xib实现如下的自定义单元格:白底圆角,左侧是标题文本,右侧是图片。
注意:设置约束时去掉“Constrain to margins”的勾选,这样做防止自动添加外边距。
(4)接着往新增的View组件里面拖入一个 Image View 组件和一个 Lable 组件(lines属性设为2),并添加相关的约束 (5)把xib中新增的三个组件在对应的类中做代码关联。同时在初始化函数 awakeFromNib() 中设置圆角 代码如下
import UIKit
class MyTableViewCell: UITableViewCell {
@IBOutlet weak var customView: UIView!
@IBOutlet weak var customLabel: UILabel!
@IBOutlet weak var customImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
//设置cell是有圆角边框显示
customView.layer.cornerRadius = 8
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
3,自定义cell组件的使用
代码如下
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableData = [["title":"Swift - 让标签栏按钮UITabBarItem图片居中","image":"img1.png"],
["title":"Swift - 使用SSZipArchive实现文件的压缩、解压缩","image":"img2.png"],
["title":"Swift - 使用LINQ操作数组/集合","image":"img3.png"],
["title":"Swift - 给表格UITableView添加索引功能","image":"img4.png"],
["title":"Swift - 列表项尾部附件点击响应","image":"img5.png"],
["title":"Swift - 自由调整图标按钮中的图标和文字位置","image":"img6.png"]]
var tableView:UITableView?
override func loadView() {
super.loadView()
}
override func viewDidLoad() {
super.viewDidLoad()
//创建表视图
self.tableView = UITableView(frame: UIScreen.mainScreen().applicationFrame,
style:.Plain)
self.tableView!.delegate = self
self.tableView!.dataSource = self
//设置表格背景色
self.tableView!.backgroundColor = UIColor(red: 0xf0/255, green: 0xf0/255,
blue: 0xf0/255, alpha: 1)
//去除单元格分隔线
self.tableView!.separatorStyle = .None
//创建一个重用的单元格
self.tableView!.registerNib(UINib(nibName:"MyTableViewCell", bundle:nil),
forCellReuseIdentifier:"myCell")
self.view.addSubview(self.tableView!)
}
//在本例中,只有一个分区
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
//返回表格行数(也就是返回控件数)
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableData.count
}
//单元格高度
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath)
-> CGFloat {
return 100
}
//创建各单元显示内容(创建参数indexPath指定的单元)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell
{
let cell:MyTableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell")
as! MyTableViewCell
let item = tableData[indexPath.row]
cell.customLabel.text = item["title"]
cell.customImage.image = UIImage(named:item["image"]!)
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}