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;
}
结果如图所示: