29,041
社区成员
发帖
与我相关
我的任务
分享
/**
*TestCell.h
*/
@interface TestCell : UITableViewCell
//cell高度由自己的内容决定
@property(nonatomic,assign) CGFloat *cellHeight;
@property(nonatomic,weak) UILabel *label;
@end
/**
*TestCell.m
*/
@implementation TestCell
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
NSLog(@"初始化cell");
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self != nil) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
_label = label;
[self addSubview:label];
}
return self;
}
@end
/**
*TestTableCtr.m
*/
@interface TestTableCtr ()
@property(nonatomic,strong)NSMutableArray *tableData;
@end
@implementation TestTableCtr
-(NSMutableArray *)tableData{
if (_tableData == nil) {
_tableData = [NSMutableArray array];
for (int i=0; i<50; i++) {
[_tableData addObject:[NSString stringWithFormat:@"第%d行",i]];
}
}
return _tableData;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//方式1:先取到cell,再根据cell的高度返回对应的高度,但是这种方式cell的重用就有问题,cell会初始化很多次
TestCell *cell = (TestCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
//方式2:直接返回定死的高度,这样cell重用没有问题,但不能动态返回高度
//return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"生成一个cell");
static NSString *identifier = @"identifier";
TestCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[TestCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.label.text = _tableData[indexPath.row];
cell.bounds = CGRectMake(0, 0, cell.bounds.size.width, 20 + indexPath.row);
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.tableData.count;
}
@end
///Cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//取得cell
AppointmentHisCell *cell = (AppointmentHisCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
//计算高度
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return height;
}
我看网上的文章用xib定义cell然后自动布局就是这样写的,但是我就发现在-tableView:heightForRowAtIndexPath:里面用-tableView:cellForRowAtIndexPath:这个方法,cell重用就有问题,如果不能这样调用,那用xib定义cell,用自动布局又该怎样计算高度呢?