class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
//设置5行单元格
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
//设置单元格的高度
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "resedCell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
if (cell == nil)
{
cell=UITableViewCell(style: .subtitle, reuseIdentifier: identifier)
//如果在可重用单元格队列中,没有可以重复使用的单元格,则创建新的单元格,新的单元格具有自标题的单元格形式,并拥有一个复用标识符
}
cell?.textLabel?.text = "Cell title here."
//子标题样式的单元格,拥有一个标签对象,再次设置标签对象的文字内容
cell?.detailTextLabel?.text = "Detail information here"
//子标题样式中,下方还有一个字体较小的描述文字标签,同样设置该标签对象的文字内容
return cell!
}
运行结果
在视图控制器,需要继承单元格的协议以及数据源
let star = UIImage(named: "81552986130_.pic")
let starGray = UIImage(named: "41552986126_.pic")
cell?.imageView?.image = starGray
//设置单元格的默认图标
cell?.imageView?.highlightedImage = star
//设置单元格点击后的图标
设置单元格的背景颜色
let rowNum = (indexPath as NSIndexPath).row
//在这里设置单元格的识别
if(rowNum==1)
{
cell?.backgroundColor = UIColor.yellow
}
else
{
let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
let view = UIView(frame: rect)
view.backgroundColor = UIColor.brown
cell?.backgroundView = view
}