iOS——自定义cell

iOS——自定义cell

首先我们在自定义cell时,需要先创建一个继承于UITableViewCell的子类,然后在.h文件中添加我们所需要的属性。

@interface MyTableViewCell : UITableViewCell
@property(nonatomic , strong)UILabel* lable;
@end

像这样,然后我们在它的.m文件中增加两个方法

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    self.lable = [[UILabel alloc] init];
    [self.contentView addSubview: self.lable];
    return self;
}
- (void)layoutSubviews {
    [super layoutSubviews] ;
    _lable.frame = CGRectMake(20, 20, 100, 100);
}

第一个方法是我们增加创建lable并且将它增加,第二个方法是设置布局。

之后我们在 ViewController.h文件中完成对两个协议的遵守:

<UITableViewDelegate,
UITableViewDataSource
>

并且声明新属性

@property(nonatomic, strong)UITableView* tableView;

然后我们在ViewController.m文件中完成判断,并且完成自定义cell

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[MyTableViewCell class] forCellReuseIdentifier:@"od"];
    [self.view addSubview:_tableView];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: @"od"];
    if(!cell) {
        cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"od"];
        // cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    cell.lable.text = @"STA";
    return cell;
}
 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   return 10;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

结果如图所示:

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值