美文网首页iOS UI控件
iOS TableView Cell的创建和使用(入门级)

iOS TableView Cell的创建和使用(入门级)

作者: momoxiaoming | 来源:发表于2017-09-27 17:30 被阅读0次

    首先开启自适应高度,开启后无需再重写高度方法,但必须在cell中内容上下顶到(好处多多,推荐使用)

    
    //开启高度自适应
    
    self.tableView.estimatedRowHeight = 250.0f;
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    //去除下横线
    
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    

    一.通过注册方式加载cell(好处在于无需自己判空操作,个人推荐使用该种方式,因为更清晰)

    1.如果cell视图是通过xib创建的,注册xib
    
    [ self.table registerNib:[UINib nibWithNibName:@"NearyCell" bundle:nil]  forCellReuseIdentifier:@"NearyCell"];
    
    
    2.如果cell视图是通过代码创建,注册class
    
    [self.table registerClass:[Neary2Cell class] forCellReuseIdentifier:@"NearyCell"];
    
    //注册后系统默认调用了cell的initWithStyle初始化方法
    
    
    在tableview 协议方法中
    
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    /
    
    //使用该种方式,需先注册cell,系统会自动查找我们注册的cell,并自动创建
    
    Neary2Cell *cell=[tableView dequeueReusableCellWithIdentifier:@"NearyCell" forIndexPath:indexPath];
    
    return cell;
    
    }
    
    

    二.通过非注册方式加载cell(需要自己判空操作,但是无需注册)

    在tableview 协议方法中
    1.代码创建的cell
    
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    /
    
    //需手动判空,cell为空的时候通过initWithStyle创建cell
    
    Neary2Cell *cell=[tableView dequeueReusableCellWithIdentifier:@"Neary2Cell"];
    
    if(!cell){
    
    cell=[[Neary2Cell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Neary2Cell"];
    
    }
    
    return cell;
    
    }
    
    
    2.xib创建的cell
    
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //需手动判空,cell为空的时候通过initWithStyle创建cell
    
    Neary2Cell *cell=[tableView dequeueReusableCellWithIdentifier:@"Neary2Cell"];
    
    if(!cell){
    
    cell=[[[NSBundle mainBundle] loadNibNamed:@"Neary2Cell" owner:nil options:nil] firstObject];
    
    }
    
    return cell;
    
    }
    
    

    相关文章

      网友评论

        本文标题:iOS TableView Cell的创建和使用(入门级)

        本文链接:https://www.haomeiwen.com/subject/pbnuextx.html