iOS开发

UItableView的cell优化

2019-04-12  本文已影响0人  追逐_chase

tableViewCell的常见设置

// 取消选中的样式(常用) 让当前 cell 按下无反应
cell.selectionStyle = UITableViewCellSelectionStyleNone;

// 设置选中的背景色
UIView *selectedBackgroundView = [[UIView alloc] init];
selectedBackgroundView.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = selectedBackgroundView;

// 设置默认的背景色
cell.backgroundColor = [UIColor blueColor];

// 设置默认的背景色
UIView *backgroundView = [[UIView alloc] init];
backgroundView.backgroundColor = [UIColor greenColor];
cell.backgroundView = backgroundView;

// backgroundView的优先级 > backgroundColor
// 设置指示器
//设置辅助类型
//    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

cell.accessoryView = [[UISwitch alloc] init];

//优先级 accessoryView >  accessoryType



TableViewCell的循环使用

循环使用的原理

优化方式一

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //定义重用标识
    //static修饰的局部变量 只会初始化一次,分配一次内存
    static NSString *ID = @"cell";
    //在缓存池中寻找cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    //没有找到创建cell
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    
    return cell;
}

优化方式二 注册 cell

// 定义重用标识
NSString *ID = @"cell";
- (void)viewDidLoad {
    [super viewDidLoad];
   //注册cell
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
    
    //UITableViewCell 可以是自己 自定义的cell
    //也可以通过nib创建的

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //去缓存池中查找cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

    // 
    cell.textLabel.text = [NSString stringWithFormat:@"cell - %zd", indexPath.row];

    return cell;
}


优化方式3 --通过SB创建UITableViewController自带的cell

Snip20150602_152.png Snip20150602_153.png


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  //先根据cell的标识去缓存池中查找可循环利用的cell
  UITableViewCell *cell = [tableView   dequeueReusableCellWithIdentifier:ID];
  // 
 cell.textLabel.text = [NSString stringWithFormat:@"cell - %zd", indexPath.row];

    return cell;
}


上一篇 下一篇

猜你喜欢

热点阅读