自定单元格标签中的文本与块一起显示。 有没有更好的方法来实现这一目标?
CustomCell.h
@interface CustomCell : UITableViewCell
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIView *circle;
@end
CustomCell.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];
}
表视图.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 显示文本的唯一方法是使用上面的块。 如果我不使用块而只是使用cell.Label.text = @"This is a Label"
后跟[cell setNeedsDisplay];
,则文本不会出现,我必须滚动表格视图导致单元格重新加载,然后标签中的文本才最终出现。
有没有更好的方法,或者我不得不使用块?
调用单元格的 layoutSubviews
方法之前,不会为 label
属性创建UILabel
,该方法是在尝试在表视图控制器中设置标签文本很久之后。
将标签的创建移动到自定义单元格的initWithStyle:reuseIdentifier:
方法。还要在 init...
方法中调用self.contentView addSubview:
。layoutSubviews
方法中唯一应该做的是标签框架的设置。
完成此操作后,您将不需要在cellForRow...
方法中使用GCD。
也对circle
属性执行相同的操作。
顺便说一句 - 您使用 GCD 可以解决问题,因为它为单元格提供了要调用layoutSubviews
方法的更改,从而创建标签。
首先,您不应该在 layoutSubviews 中分配和放置视图。应在创建单元格时创建并放置视图,并且只需在 layoutSubviews 方法中更改框架(如果需要)。否则,您将获得大量重复的视图。
接下来,您不应该在 tableView:cellForRowAtIndexPath: 中使用 dispatch_async。您可以直接设置文本标签。你也不应该需要setNeedsDisplay,因为系统无论如何都会用新单元格做到这一点。