【问题标题】:UITableViewCell custom subviewsUITableViewCell 自定义子视图
【发布时间】:2014-02-20 00:46:49
【问题描述】:

我的控制器中有这个:

- (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,我在哪里设置子视图值(imageviews 图像,labels 文本等...)基于该_post??

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

【问题讨论】:

  • 在您的setPost 函数中,您需要创建一个视图(无论您需要什么类型),然后将该视图添加为您的单元格的子视图:[self.contentView addSubview:newView]。然后对您希望单元格包含的任何其他视图再次执行此操作。

标签: ios objective-c cocoa-touch uitableview subview


【解决方案1】:
- (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 中运行良好,没有任何滞后。

【讨论】:

    【解决方案2】:
    - (void)setPost:(Post *)newPost
    {
        if (_post != newPost) {
            _post = newPost;
        }
        //check subviews exist and set value by newPost, if need no view, add subview, if need value, set new value
        //Following code is just sample.
        if(!self.imageView){
           self.imageView = [[UIImageView alloc] init];
           [self.contentView addSubview:self.imageView];
        }
    
        if(newImage){
            self.imageView = newImage;
        }
    
        [self setNeedsDisplay];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多