OC-自定义Cell

1.UITableViewCell的组成

内容视图
系统版
….
自定义:
1.创建要显示的控件
2.将创建好的控件以子视图的形式,添加到cell.contentView中即可

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
    }

    //从cell中获取label
    UILabel *label = [cell.contentView viewWithTag:100];
    //如果没有取出 创建一个添加到 cell.contentView 上
    if(label == nil) {
        label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 60)];
        label.tag = 100;
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:32];
        //将label添加到cell.contentView 上
        [cell.contentView addSubview:label];
    }
    label.text = [NSString stringWithFormat:@"第%ld行",indexPath.row];


    //第一行的辅助视图是个开关控件
    if(indexPath.row == 1) {
        UISwitch *mySwitch = [[UISwitch alloc]init];
        [mySwitch addTarget:self action:@selector(clickSwitch:) forControlEvents:UIControlEventValueChanged];
        //将控件赋值给cell.accessoryView
        cell.accessoryView = mySwitch;
    }else {
        cell.accessoryView = nil;
    }


    return cell;
}
//通过属性设置行高
self.tableView.rowHeight = 60;

//cell不设置高度的话 默认高度44  如果希望不是44 可以自己设置
//通过代理方法设置 也可以 通过属性设置
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return 60;
//}

辅助视图
系统版
….
自定义
1.创建要显示的控件
2.将创建好的控件赋值给cell.accessoryView即可

2.单元格的重用

重用方式一:
核心:如果没有取出,自己创建
原理:系统会将那么超出屏幕,看不见的单元格对象回到到tableView的一个队列中存储,在需要一个cell对象先尝试从队列中取,看有没有已经回收的cell,如果有把这个cell从队列中取出继续使用,如果没有取出我们就创建新的cell
重用方式二:
核心:如果没有取出,系统自动创建
原理:在开始的时候向系统注册一个cell类型的样式,系统会将那么超出屏幕,看不见的单元格对象回到到tableView的一个队列中存储,在需要一个cell对象先尝试从队列中取,看有没有已经回收的cell,如果有把这个cell从队列中取出继续使用,如果没有系统会根据我们之前注册的样式帮我们创建一个cell使用

- (void)viewDidLoad {
    [super viewDidLoad];
    //向tableview中注册一个 cell类型 的样式
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellID"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 30;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //重用方式二 如果没有取出 tableView会根据之前注册的帮我们创建一个cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];

    cell.textLabel.text = @"这是一个单元格";

    return cell;
}

3.表格结合各种数据模型的显示

【前提:表格的行数是不定,也叫动态表格】
1.将数组显示到表格中
2.将对象数组显示到表格中

cell.textLabel.text = self.datas[indexPath.row];
发布了52 篇原创文章 · 获赞 5 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/shuan9999/article/details/52496032