此次咱们来分享一下关于 UITableView 的一个开发小技巧, 后面我会陆续的把关于 UITableView 的其余开发小技巧补充上, 废话少说, 让咱们来看看代码ruby
关于怎么快速添加一个 UINavigationController 在上两篇文章里有讲解, 这里就不说了, 下面让咱们来看看代码.markdown
遵照代理协议和数据源协议ide
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {}
设置代理对象布局
override func viewDidLoad() {
super.viewDidLoad()
myTableView.delegate = self
myTableView.dataSource = self
}
获取属性和声明数据ui
@IBOutlet weak var myTableView: UITableView!
let stringArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"]
实现代理方法和数据源方法spa
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)
}
好了, 此次咱们就讲到这里, 下次咱们继续~~~code