本文将演示单元格背景颜色的设置
在项目导航区,打开视图控制器的代码文件【ViewController.swift】
1 import UIKit 2 3 //首先添加两个协议。 4 //一个是表格视图的代理协议UITableViewDelegate 5 //另一个是表格视图的数据源协议UITableViewDataSource 6 class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 7 8 override func viewDidLoad() { 9 super.viewDidLoad() 10 // Do any additional setup after loading the view, typically from a nib. 11 12 //创建一个位置在(0,40),尺寸为(320,420)的显示区域 13 let rect = CGRect(x: 0, y: 40, 320, height: 420) 14 //初始化一个表格视图,并设置其位置和尺寸信息 15 let tableView = UITableView(frame: rect) 16 17 //设置表格视图的代理,为当前的视图控制器 18 tableView.delegate = self 19 //设置表格视图的数据源,为当前的视图控制器 20 tableView.dataSource = self 21 22 //将表格视图,添加到当前视图控制器的根视图中 23 self.view.addSubview(tableView) 24 } 25 26 //添加一个代理方法,用来设置表格视图,拥有单元格的行数 27 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 28 //在此设置表格视图,拥有7行单元格 29 return 7 30 } 31 32 //添加一个代理方法,用来初始化或复用表格视图中的单元格 33 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 34 35 //创建一个字符串,作为单元格的复用标识符 36 let identifier = "reusedCell" 37 //单元格的标识符,可以看作是一种复用机制。 38 //此方法可以从,所有已经开辟内存的单元格里面,选择一个具有同样标识符的、空闲的单元格 39 var cell = tableView.dequeueReusableCell(withIdentifier: identifier) 40 41 //判断在可重用单元格队列中,是否拥有可以重复使用的单元格。 42 if(cell == nil) 43 { 44 //如果在可重用单元格队列中,没有可以重复使用的单元格, 45 //则创建新的单元格。新的单元格具有系统默认的单元格样式,并拥有一个复用标识符。 46 cell = UITableViewCell(style: .default, reuseIdentifier: identifier) 47 } 48 49 //默认样式的单元格,拥有一个标签对象,在此设置标签对象的文字内容。 50 cell?.textLabel?.text = "Title Information" 51 52 //索引路径用来标识单元格在表格中的位置。它有section和row两个属性, 53 //section:标识单元格处于第几个段落 54 //row:标识单元格在段落中的第几行 55 //获取单元格在段落中的行数 56 let rowNum = (indexPath as NSIndexPath).row 57 58 //如果处于第2行,则设置该单元格的背景颜色为黄色(第一行索引为0) 59 if(rowNum == 1) 60 { 61 cell?.backgroundColor = UIColor.yellow 62 } 63 else 64 { 65 //创建一个位置在(0,0),尺寸为(100,100)的显示区域 66 let rect = CGRect(x: 0, y: 0, 100, height: 100) 67 //并初始化一个视图,同时设置其位置和尺寸信息 68 let view = UIView(frame: rect) 69 //设置视图的背景颜色为棕色 70 view.backgroundColor = UIColor.brown 71 72 //然后将设置好的视图,作为单元格的背景视图 73 cell?.backgroundView = view 74 } 75 76 //返回设置好的单元格对象。 77 return cell! 78 } 79 80 override func didReceiveMemoryWarning() { 81 super.didReceiveMemoryWarning() 82 // Dispose of any resources that can be recreated. 83 } 84 }