UITableView 自定义UITableViewCell

自定义UITableViewCell 步骤:

这里拿带有checkBox按钮的UITableViewCell作为例子。先上效果图

先新增加个类:CheckBoxCell继承自UITableViewCell。

分别修改CheckBoxCell.h和CheckBoxCell.m.增加4个输出口:

IBOutlet UIImageView *theImage;
    IBOutlet UILabel *nameLabel;
    IBOutlet UILabel *theDetailLabel;
    IBOutlet UIButton *checkBoxBtn; 

设置相对应的@property和@synthesize

然后再加入一个xib文件取名和新增加的类名一致CheckBoxCell。

分别拖拽进来一个UITableViewCell,两个label,一个button。CheckBox框其实是一个按钮(custom),对应的image看上去像是传统的checkBox。

修改CheckBoxCell.xib文件。首先修改对应的class为CheckBoxCell,接着修改UITableViewCell的Identifier(随便起:myCell).然后连上各自的输出口。注意:这里连接的不是File‘s Owner 而是文件本身。

在UITableVIew里使用自定义的Cell。
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellStr= @"myCell";
    CheckBoxTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (cell == nil) {
            NSArray *arr=[[NSBundle mainBundle]loadNibNamed:@"CheckBoxTableCell" owner:self options:nil];
            if(arr&&[arr count]>0){
                cell=[arr objectAtIndex:0];
            }
    }
 }

采用自定义的cell以后,有个问题。就是UITableVIew的单击方法didSelectRowAtIndexPath 有时能用,有时不能用。发现是点击子控件的不行,其它区域可以。解决办法:

在Cell上加一个手势:

    UITapGestureRecognizer *tap1=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doSelectedCell:)];
    tap1.cancelsTouchesInView = NO;
    [cell addGestureRecognizer:tap1];
    [tap1 release];

-(void)doSelectedCell:(UITapGestureRecognizer*)sender{
    CGPoint point=[sender locationInView:self.view];
    NSIndexPath *path=[myTableView indexPathForRowAtPoint:point];
    [self tableView:myTableView didSelectRowAtIndexPath:path];
}

并且可以通过indexPathForRowAtPoint方法,获得点击处的cell。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值