ios - 在创建时调整自定义 UITableViewCell 的 subview

标签 ios objective-c uitableview

我正在尝试使用自己的 XIB 创建自定义 UITableViewCell,其中包含两个重要的可编辑组件:

  • 界面标签
  • 带有“end-cap insets”的 UIImage - 此图像位于标签后面,并随其调整大小

当我创建我的 UITableViewCell 时,我可以很容易地设置它的标签文本,但我也用同样的方法尝试更改 UIImage 的框架以匹配 UILabel 的框架。但是,直到我通过滚动 TableView 将其出列并重新显示在 View 中来“重新加载”单元格时,才会发生这种情况。

我在我的 View Controller 的 .m 中创建自定义表格 View 单元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *UITableViewCellIdentifier = @"msgCell";

    RMMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:UITableViewCellIdentifier];

    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MessageCell" owner:self options:nil];
        cell = [topLevelObjects objectAtIndex:0];
        [cell customInit]; //This sets up the ImageView's image etc
    }

    [cell setMessageValue:[_messages objectAtIndex:indexPath.row]]; //SEE BELOW

    return cell;
}

...在我的自定义单元格的 .m 中,我使用此方法处理设置文本标签和调整图像大小:

- (void)setMessageValue:(NSString *)message {

    _testLabel.text = message;
    // Assume the text label's frame has already been set to the message's length 
    // (will add this in once I figure out how to change the imageView's 
    // frame correctly)

    // Set the image view's frame to the label's
    // THIS DOES NOT TAKE EFFECT UNTIL THE TABLE VIEW IS RE-SCROLLED
    CGRect frame = _imageView.frame;
    frame.size.width = _testLabel.frame.size.width + 8;
    _imageView.frame = frame;
}

最佳答案

这是因为一个table view cell是按一个尺寸创建的,然后添加到表格后显示的时候再调整尺寸造成的。如果您记录单元格的边界或框架,当您从 Nib 加载它时,您会看到它是一个尺寸(较小),而当您通过将其滚动到屏幕之外来“刷新”单元格时,您会看到它是另一个尺寸(更大)然后继续。

最简单的方法是确保标签和图像都具有相同的自动调整大小规则,以便在调整单元格大小时它们一起增长。

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

相关文章:

IOS7 UITableView 在设置应用程序中分组

iphone - iOS 自定义按钮和 slider 的免费位图?

ios - [UIImageView CGImage] : unrecognized selector sent to instance 0x1783e5b00

objective-c - 在 Objective-C 中除以 int 并向上取整

ios - ScrollView 或 TableView 标题中的 UITable?

objective-c - 键值编码的要点是什么?

iphone - 如何创建像联系人应用程序那样的可编辑 UITableView? (iPhone)

ios - 为什么在iOS中使用核心图形绘制的线的连接处会出现一个点?

ios - 使用 RxSwift 创建一个可观察对象

ios - 如何快速在特定表格 View 行执行特定操作?