现在的位置: 首页 > 综合 > 正文

UITableView 自定义UITableViewCell

2013年02月02日 ⁄ 综合 ⁄ 共 1568字 ⁄ 字号 评论关闭

自定义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。

抱歉!评论已关闭.