自定义cell的几种方法。

1.第一种方式。

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

{

    

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {

     //创建要自定义的子控件,设置属性,在cell上加一个label。

        UILabel *addressLab = [[UILabel alloc]init];

        addressLab.font = kMiniFont;

        addressLab.textColor = kDarkgrayColor;

        [self addSubview:addressLab];

        _addressLab = addressLab;

    }

    return self;

}

//布局子控件,cell创建完毕,自动调用此方法。不需要主动调用。

- (void)layoutSubviews

{

    [super layoutSubviews];

//布局上边的addressLab。

 _addressLab.frame = CGRectMake(labX, addressLabY, 150, 30);

}

2.第二种方式

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

{

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    

    if (self)

    {

//定义子控件,

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

//        flowLayout.minimumLineSpacing = 5;

//        flowLayout.minimumInteritemSpacing = 5;

        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];

        collectionView.backgroundColor = [UIColor clearColor];

        collectionView.delegate = self;

        collectionView.dataSource = self;

        [collectionView setScrollEnabled:NO];

        _collectionView = collectionView;

        

        [collectionView registerClass:[MTCollectionViewCell class] forCellWithReuseIdentifier:@"GradientCell"];

        [self.contentView addSubview:_collectionView];

   }

    return self;

}

//自定义一个方法,布局子控件,在cell创建完成时调用即可。

- (void)adjustmentFrame

{

     commentBtnView.frame = CGRectMake(0, y, w, commentBtnH - 1);

}

我这里在Controller.m文件中调用此方法,如下

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

{

//在此方法最后调用,来布局子控件

[cell adjustmentFrame];

    return cell;

}

3.用xib自定义cell。

用xib自定义一个cell,modelCell.xib

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

{

    NSString *identifier = [NSString stringWithFormat:@"identifier %d",indexPath.row];

    

    MTScenicCommentInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    

    if (cell == nil)

    {

//在这加载xib文件

        cell =  [[NSBundle mainBundle] loadNibNamed:@"modelCell" owner:self options:nil] lastObject];

    }

     return cell;

}

posted on 2015-01-06 18:06  rankilau  阅读(399)  评论(0编辑  收藏  举报

导航