这次我们来分享一下关于 UITableView 的一个开发小技巧, 后面我会陆续的把关于 UITableView 的其他开发小技巧补充上, 废话少说, 让我们来看看代码
1.界面布局
关于怎么快速添加一个 UINavigationController 在上两篇文章里有讲解, 这里就不说了, 下面让我们来看看代码.
2.实现代码
遵守代理协议和数据源协议
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {}
设置代理对象
override func viewDidLoad() { super.viewDidLoad() myTableView.delegate = self myTableView.dataSource = self }
获取属性和声明数据
@IBOutlet weak var myTableView: UITableView! let stringArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"]
实现代理方法和数据源方法
func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return stringArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) as! UITableViewCell cell.textLabel!.text = stringArray[indexPath.row] return cell }
实现自定义方法
func colorForIndex(index: Int) -> UIColor { let itemCount = stringArray.count - 1 let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6 return UIColor(red: 0.8, green: color, blue: 0.2, alpha: 1.0) } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.backgroundColor = colorForIndex(indexPath.row) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.myTableView.deselectRowAtIndexPath(indexPath, animated: true) }
3.最终效果
好了, 这次我们就讲到这里, 下次我们继续~~~