iOS7:没有 GCD,自定义单元格中的 UILabel 文本不会出现

标签 ios uitableview ios7

自定义单元格标签中的文本显示为一个 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/

相关文章:

objective-c - 获取 UIGestureRecognizer 的 UITouch 对象

ios - 通过 simctl 安装 WatchKit 应用程序

ios - UITableViewCell ImageView 不更新

ios - UIRefreshControl 和 UITableView 反弹的问题

iOS UIWebView Javascript 定时器

ios - 如何使 NSSortDescriptor 不按字母顺序排列?

ios - 如何找到崩溃发生的位置 - ios

ios - 快速限制阵列容量会更有效吗?

ios - 关于将光标位置放置在空文本字段中的查询

javascript - 禁用 IOS Safari 弹性滚动