自定义单元格标签中的文本显示为一个 block 。有没有更好的方法来实现这一目标?
自定义单元格.h
@interface CustomCell : UITableViewCell
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIView *circle;
@end
自定义单元格.m
@implementation CustomCell
- (void)layoutSubviews
{
[super layoutSubviews];
self.circle = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 40.0f, 40.0f)];
[self.circle setBackgroundColor:[UIColor brownColor];
self.label = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 200.0f, 50.0f)];
self.label.textColor = [UIColor blackColor];
[self.contentView addSubview:self.label];
[self.contentView addSubview:self.circle];
//I have also tried [self addSubview:self.label];
}
表格 View .m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *customCellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:customCellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:inviteCellIdentifier];
}
dispatch_async(dispatch_get_main_queue(), ^{
[[cell label] setText:@"This is Label"];
[cell setNeedsDisplay];
});
return cell;
}
让 UILabel 显示文本的唯一方法是使用上面的 Block。如果我不使用该 block 而只是使用 cell.Label.text = @"This is a Label"
后跟 [cell setNeedsDisplay];
,文本不会出现,我必须滚动 tableview 导致单元格重新加载,然后标签中的文本才最终出现。
有没有更好的方法,还是我不得不使用该 block ?
最佳答案
在调用单元格的 layoutSubviews
方法之前,您不会为 label
属性创建 UILabel
,这在您尝试设置很久之后 TableView Controller 中的标签文本。
将标签的创建移至自定义单元格的 initWithStyle:reuseIdentifier:
方法。还将对 self.contentView addSubview:
的调用放在 init...
方法中。 layoutSubviews
方法中唯一应该做的是标签框架的设置。
一旦你这样做了,你就不需要在 cellForRow...
方法中使用 GCD。
也为 circle
属性做同样的事情。
顺便说一句 - 您使用 GCD 解决了这个问题,因为它为要调用的 layoutSubviews
方法更改了单元格,创建了标签。
关于iOS7:没有 GCD,自定义单元格中的 UILabel 文本不会出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21821380/