您的位置:首页 > 产品设计 > UI/UE

UITableView详解(UITableViewCell(二) 自定义cell)

2014-03-11 08:56 337 查看
     上一节中,我们定义的cell比较单一,只是单调的输入文本和插入图片,但是在实际开发中,有的cell上面有按钮,有的cell上面有滑动控件,有的cell上面有开关选项等等,具体参加下面2个图的对比:




@我们可以通过2种方式来实现自定义,一是利用系统的UITableViewCell(但不推荐,因为开发效率不高),举例:还是在这个关键方法中

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * cellIdentifier  = @"cell";
    UITableViewCell * cell = [tableViewdequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellIdentifier];
     // 首先,各种按钮控件的初始化,一定要放在这个if语句里面,如果放在这个大括号外面,cell被执行n次,那么一个cell上面就会被添加n个控件
     // 其次,你在这个括号里面自定义初始化控件后,如果你想给每一个cell的控件显示不同的内容和效果,你在括号外面是取不到对象的,只有通过设置它们继承UIView的属性tag来标识,我们可以想一想,如果控件一多或者别人来接受你的项目,你自己定义了很多的tag,这样合作的效率不高,所以主要推荐第二种
    }
    return cell;
}
@二是,创建UITableViewCell子类,在contentView上实现自定义效果(cell上的所有内容都是显示在cell的属性contentView上),这里也是写这个方法
#import <UIKit/UIKit.h>

@interface HMTAssistCell : UITableViewCell

@property (nonatomic) UILabel * label;
@property (nonatomic) UIButton * button;

@end

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {

_button = [UIButton buttonWithType:UIButtonTypeSystem];
_button.backgroundColor = [UIColor redColor];
_button.frame = CGRectMake(150, 60, 50, 100);
[_button setTitle:@"油条" forState:UIControlStateNormal];
[self.contentView addSubview:_button];

_label = [[UILabel alloc]initWithFrame:CGRectMake(10, 30, 100, 100)];
_label.backgroundColor = [UIColor greenColor];
[self.contentView addSubview:_label];

}
return self;
}

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

// 依旧设置重用标识
static NSString * cellIdentifier  = @"cell";

// 这里用我们新建的UITableViewCell的子类进行cell重用声明
HMTAssistCell * cell = (HMTAssistCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

// 如果没有,则创建
if (!cell) {

cell = [[HMTAssistCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

}

// 因为_label是类HMTAssistCell中的属性,所以就能很方便的取出来进行赋值
cell.label.text = [NSString stringWithFormat:@"%d",indexPath.row];

return cell;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  UI uitableviewcell