ios - UITableViewCell 自定义 subview

标签 ios objective-c cocoa-touch uitableview subview

我的 Controller 里有这个:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"PostCell";

    PostCell *postCell = (PostCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...
    Post *post = self.displayPosts[indexPath.row];
    [postCell setPost:post];

    return postCell;
}

使用 [postCell setPost:post]; 我发送了我将要使用的自定义单元格模型。

- (void)setPost:(Post *)newPost
{
    if (_post != newPost) {
        _post = newPost;
    }
    [self setNeedsDisplay];
}

现在这是我拥有的版本,但我想更改它。现在我有 [self setNeedsDisplay] 调用 drawRect - 我想使用 subviews 并且不知道如何启动它。

我在哪里添加 subviews 如果使用 IBOutlets 我在哪里设置 subview 值(imageviews image, labels 文本等...) 基于那个 _post ??

或者如果更容易指出如何使用 drawRect 向我的单元格添加 buttons 以及如何检测 drawRect 中图像和按钮上的 touch ?这样我就不需要更改当前版本。

最佳答案

- (void)setPost:(Post *)newPost
{
    if (_post != newPost) {
        _post = newPost;
    }

    [self layoutSubviews];
    [self refreshContent];
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    if (self.titleLabel == nil) {
     self.titleLabel = [[UILabel alloc] init];
     [self addSubview:self.titleLabel];
    }

    if (self.imageView == nil) {
     self.imageView = [[UIImageView alloc] init];
     [self addSubview:self.imageView];
    }

    // here I also set frames of label and imageview

}

- (void)refreshContent
{
    [self.titleLabel setText:_post.title];
    [self.imageView setImage:self.post.image];
}

这就是我完成它的方式,它在 UITableView 中没有任何滞后,效果很好。

关于ios - UITableViewCell 自定义 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21895861/

相关文章:

objective-c - 将 [touches anyObject] 更改为与数组中的任何对象接触

objective-c - 对类和对象 iVar 感到困惑

iphone - 在获取 UITableView Section 和 Row 之后...这段代码做了什么?

ios - 如何将 UIButton 的标题设置为左对齐?

ios - swift 中的 Firebase 查询排序顺序?

iOS8 phonegap cordova 网络信息应用程序崩溃

objective-c - 检查我的应用程序用户使用的 iOS 版本

php - 从iPhone将大型视频上传到Web服务器

iphone - CIFilter filterWithName :keysAndValues: set keysAndValues from NSDictionary

ios - 将自定义对象存储在UILocalNotification的userInfo中而不进行编码