iOS控件学习笔记-UITableView自定义cell

初始化

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0,kWidth,kHeight) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
	//[self.tableView registerClass:[ZJTableViewCell class] forCellReuseIdentifier:@"cell"];
	
    
代理和数据源
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    ZJTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell){
        cell = [[ZJTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.student = self.array[indexPath.row];

    }
    return cell;
}

ZJTableViewCell.h

#import <UIKit/UIKit.h>
@class Student;

NS_ASSUME_NONNULL_BEGIN

@interface ZJTableViewCell : UITableViewCell
@property(nonatomic,strong)Student *student;
@end

NS_ASSUME_NONNULL_END

ZJTableViewCell.m

#import "ZJTableViewCell.h"
#import "Student.h"

@interface ZJTableViewCell()
@property(nonatomic,strong)UILabel *desLbl;
@end

@implementation ZJTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    
    if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]){
        //初始化并添加子控件(设置字体、文字颜色等)
        self.desLbl = [[UILabel alloc]init];
        [self.contentView addSubview:self.desLbl];
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    //计算和设置所有子控件的frame
    self.desLbl.frame = CGRectMake(100,10,100,20);
}

- (void)setStudent:(Student *)student{
    self.student = student;
    self.desLbl.text = self.student.name;
    
}

@end
发布了38 篇原创文章 · 获赞 5 · 访问量 9063

猜你喜欢

转载自blog.csdn.net/zj382561388/article/details/103143929