设置 UITableView 中 cell 的背景颜色。ide
示例1:经过 backgroundView 设置。spa
1 UIView *view1 = [[UIView alloc] init]; 2 view1.backgroundColor = [UIColor blueColor]; 3 cell.backgroundView = view1;
示例2:经过 backgroundColor 设置。code
1 cell.backgroundColor = [UIColor blueColor];
backgroundView 的优先级比 backgroundColor 高,若是同时设置了, backgroundView 会覆盖 backgroundColor 。对象
设置 cell 选中状态的背景。blog
1 UIView *view2 = [[UIView alloc] init]; 2 view2.backgroundColor = [UIColor redColor]; 3 cell.selectedBackgroundView = view2;
设置 UITableView 的其余属性。字符串
1 self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; //设置分割线样式 2 self.tableView.separatorColor = [UIColor redColor]; //设置分割线颜色 3 self.tableView.tableHeaderView = [UIButton buttonWithType:UIButtonTypeContactAdd]; //设置顶部视图 4 self.tableView.tableFooterView = [[UISwitch alloc] init]; //设置底部视图
设置 cell 的 accessoryType 属性。it
accessoryType 为枚举类型,定义以下:table
1 typedef enum : NSInteger { 2 UITableViewCellAccessoryNone, 3 UITableViewCellAccessoryDisclosureIndicator, 4 UITableViewCellAccessoryDetailDisclosureButton, 5 UITableViewCellAccessoryCheckmark, 6 UITableViewCellAccessoryDetailButton 7 } UITableViewCellAccessoryType;
也可经过 cell 的 accessoryView 属性来设置辅助指示视图,以下:class
1 cell.accessoryView = [UIButton buttonWithType:UIButtonTypeContactAdd];
cell 的工做原理:在程序执行的时候,能看到多少行,就建立多少条数据。原理
缺点:若是数据量很是大,用户在短期内来回滚动,将会建立大量的 cell ,并不重用以前已经建立的 cell ,将一直开辟新的存储空间。
cell 的重用原理:当滚动列表时,部分 UITableViewCell 会移出窗口, UITableView 会将窗口外的 UITableViewCell 放入一个对象池中等待重用。当 UITableView 要求 dataSource 返回 UITableViewCell 时, dataSource 会先查看该对象池,若是池中有未使用的 UITableViewCell ,则会用新的数据来配置这个 UITableViewCell ,而后返回给 UITableView ,并从新显示到窗口中,从而避免建立新对象。所以,若是一个窗口只能显示5个 cell ,重用以后,只须要建立6个 cell 。
经过 UITableViewCell 的 reuseIdentifier 属性,可在初始化的时候传入一个特定的字符串标识符来设置。当 UITableView 要求 dataSource 返回 UITableViewCell 时,先经过该标识符到对象池中查找对应类型的 UITableViewCell 对象。若是没有,就传入这个字符串标识符初始化 UITableViewCell 对象。
1 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 2 NSLog(@"%s", __FUNCTION__); 3 static NSString *identifier = @"hero"; //保存重用的标识符 4 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; //先去对象池中查找是否有知足条件的cell 5 if (cell == nil) { 6 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier]; 7 NSLog(@"建立一个新的Cell"); 8 } 9 // 给cell设置数据 10 11 return cell; 12 }