Swift 版本: 3.讓UITableViewCell的背景色漸變
阿新 • • 發佈:2018-12-30
這次我們來分享一下關於 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.最終效果
好了, 這次我們就講到這裡, 下次我們繼續~~~