iOS大典之自定义cell


自定义cell步骤:

1: 创建一个继承自UITableViewCell的类

2: 重写初始化方法

3: 在初始化方法中, 把需要的视图加到self.contentView上面

4: 去返回cell的方法中, 把系统的 UITableViewCell 替换成你自己创建的类


例如:

音乐播放器中, 需要单独的自定义cell

来存放歌词,

歌词放在label中


创建类 LyricCell , 声明需要的属性label

#import <UIKit/UIKit.h>

@interface LyricCell : UITableViewCell



@property (nonatomic, retain) UILabel *label;



@end

重写初始化

#import "LyricCell.h"

@implementation LyricCell




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


        [self addCellSubViews];  // 调用

    }
    return  self;
}




// 添加
- (void)addCellSubViews
{

    // 添加label和cell大小一样
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    self.label.backgroundColor = [UIColor redColor];
    [self.contentView addSubview:self.label];

}

回到创建cell的控制器中, 改成自己定义的 LyricCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"GGCell";
    LyricCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];  //这里一处 

    if (cell == nil) {
        cell = [[LyricCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier]; // 这里一处

  }



    NSString *string = self.dataArray[indexPath.row];

    NSString *str = [string substringFromIndex:11];

    cell.label.text = str;  // label前加 cell.


    return cell;


}


over


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值