UI之CustomTableViewcell自定义cell(用xib)

本文介绍如何在iOS应用中使用自定义TableViewCell,并展示了完整的代码实现过程。从创建自定义单元格到设置数据源,再到调整表格视图的高度,一步步解析自定义TableViewCell的使用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


- (void)viewDidLoad {

    [super viewDidLoad];

    [self createTableView];

    [self createDataSource];

}

-(void)createTableView

{

    self.tableV=[[UITableViewalloc]initWithFrame:self.view.bounds style:0];

    self.tableV.delegate=self;

    self.tableV.dataSource=self;

   

    [self.tableV registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"cell"];

    //xib提前注册cellname后面是xib的类名,cell是重用标识符

     //新建的CustomCell必须继承于UitableViewCell

   

    [self.view addSubview:self.tableV];

}

-(void)createDataSource

{

    self.dataArr=[NSMutableArrayarray];

    for (int i=0; i<20; i++) {

        [self.dataArr addObject:@(i)];

    }

}

-(CGFloat)tableView:(UITableView*)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath*)indexPath

{

    self.tableV.rowHeight=90;

    return 90;

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}

-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.dataArr.count;

}

 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString * cellID=@"cell";

    CustomCell* cell=[tableView dequeueReusableCellWithIdentifier:cellID];

    if(cell==nil) {

        cell=[[NSBundlemainBundle]loadNibNamed:@"CustomCell" owner:self options:nil][0];

    }

     //不要在if判断外添加新的控件,会出现重影的情况(原因:tabelViewcell的重用机制)

    cell.HeaderLabel.text=@"标题";

    cell.DetailLabel.text=[NSString stringWithFormat:@"%d",indexPath.row];

    cell.HeaderImage.image=[UIImage imageNamed:@"intro_3.jpg"];

    /*

    //contentView cell的属性用来显示内容的view

    //[cell.contentView addSubview:label]

     这句代码不用写,它用于非自定制cell的属性增加

     */

    returncell;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值