自定义单元格标签中的文本随块出现。有没有更好的方法来实现这一目标?
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];
}
tableView.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。如果我不使用该块并且只使用cell.Label.text = @"This is a Label"
后面跟[cell setNeedsDisplay];
,则文本不会出现,我必须滚动tableview导致单元格重新加载,然后只有标签中的文本终于出现了。
有更好的方法还是我不得不使用该块?
答案 0 :(得分:2)
在调用单元格的UILabel
方法之前,您不会为label
属性创建layoutSubviews
,这在您尝试在表视图控制器中设置标签的文本后很长时间。
将标签的创建移动到自定义单元格的initWithStyle:reuseIdentifier:
方法。同时在self.contentView addSubview:
方法中调用init...
。 layoutSubviews
方法中唯一应该是设置标签的框架。
一旦这样做,您就不需要在cellForRow...
方法中使用GCD。
对circle
属性也这样做。
顺便说一下 - 你使用GCD解决了这个问题,因为它为单元格提供了一个变更,可以调用它的layoutSubviews
方法,从而创建标签。
答案 1 :(得分:0)
首先,您不应该在layoutSubviews中分配和放置视图。创建单元格时应创建并放置视图,并且只在layoutSubviews方法中更改框架(如果需要)。否则,你将获得一堆重复的视图。
接下来,您不应该在tableView:cellForRowAtIndexPath:中使用dispatch_async。您可以直接设置文本标签。你也不应该需要setNeedsDisplay,因为无论如何系统都会使用新单元格。