Custom Table View Cell Example
先看下最终的效果
Create a new project
新建一个 Single View Application.
Add the code
新建如下一个类
import UIKit
class MyCustomCell: UITableViewCell {
@IBOutlet weak var myView: UIView!
@IBOutlet weak var myCellLabel: UILabel!
}
新建 ViewController.swift
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// These strings will be the data for the table view cells
let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
// These are the colors of the square views in our table view cells.
// In a real project you might use UIImages.
let colors = [UIColor.blueColor(), UIColor.yellowColor(), UIColor.magentaColor(), UIColor.redColor(), UIColor.brownColor()]
// Don't forget to enter this in IB also
let cellReuseIdentifier = "cell"
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
// number of rows in table view
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as! MyCustomCell
cell.myView.backgroundColor = self.colors[indexPath.row]
cell.myCellLabel.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
Setup the storyboard
在storyboard中做如下修改
Other IB settings
还有这些
Hook Up the Outlets
- Control drag from the Table View in the storyboard to the
tableView
variable in theViewController
code. - Do the same for the View and the Label in your Prototype cell to the
myView
andmyCellLabel
variables in theMyCustomCell
class.
Finished
好了!