ios - 以编程方式创建自定义 UITableViewCell - Objective C

标签 ios objective-c uitableview

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setBackgroundColor:[UIColor clearColor]];
        //[self createViews];
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    NSLog(@"draw rect");
    [self createViews];
}

我正在创建自定义 UITableViewCell。我需要创建一个取决于 UITableViewCell 高度的 UILabel,并且高度尚未在 initWithStyle 中设置(它返回默认值 44,而实际上是我的高度细胞变化很大)。为此,我在 drawRect 中调用了我的 createViews 函数。这运行良好,但我注意到当我插入和删除行时可以再次调用该函数。

我的问题:drawRect 中调用我的 createViews 函数是否有意义?

最佳答案

您在这里几乎没有选择。

1. 使用 layoutSubviews/awakeFromNib,检查是否创建了 subview ,如果没有,则使用正确的框架创建它们。

2. 使用 init 创建 View :

  • 约束条件
  • 在没有约束的情况下,在 layoutSubviews/awakeFromNib 中尝试改变框架

关于ios - 以编程方式创建自定义 UITableViewCell - Objective C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32673046/

相关文章:

ios - kAudioFileStreamError_DiscontinuityCantRecover in AudioFileStreamParseBytes

ios - 为什么 NavgationItem 引用消失了?

ios - 修改当前用户的ACL

iphone - 完全神秘 - iOS 方法在随机延迟后执行

ios - Swift - 将数据转换为十进制值

iphone - 如何只获取对象 ID,还包括 CoreData 中的行数据?

ios - 检查在字典中保存 textfield.text 的代码

ios - 点击后 UitableView 改变 sectionView

ios - UITableView 不加载数据-带有 Xcode 7.2 的 Swift 2

ios - UITableViewCell 的 NSLayoutConstraint : Constraint must contain a first layout item