ios - layoutSubviews 在 UITableViewCell 上调用了两次

标签 ios

我正在覆盖我的 UITableViewCell 子类中的 layoutSubviews。我注意到每个单元格都调用了 layoutSubviews 两次。在第二次调用时,内容 View 框架高度比第一次调用时的高度小 1:

@implementation MyUITableViewCellCell

+ (NSString *)asString:(CGRect) rect {
     NSString *res = [[NSString alloc] initWithFormat:@"[%f %f %f %f]",
                 rect.origin.x, rect.origin.y, rect.size.width, rect.size.height];
     [res autorelease];
     return res;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    NSLog(@"Here I am %@ frame=%@ cvframe=%@,
      self.text, 
      [MyUITableViewCellCell asString:self.frame],
      [MyUITableViewCellCell asString:self.contentView.frame]);
}

@end

Controller 创建表格单元格的方式如下:

- (NSString*)dataAtIndex:(NSInteger)index
{
    NSString* data = [[NSString alloc] initWithFormat:@"Row %d", index];
    return [data autorelease];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath     *)indexPath
{
    return 30;
}

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

    NSInteger index = [indexPath row];
    MyUITableViewCellCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[MyUITableViewCellCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.text = [self dataAtIndex:index];
    return cell;
}

输出:

Here I am Row 0 frame=[0.000000 0.000000 320.000000 30.000000] cvframe=[0.000000 0.000000 320.000000 30.000000]
Here I am Row 1 frame=[0.000000 30.000000 320.000000 30.000000] cvframe=[0.000000 0.000000 320.000000 30.000000]
Here I am Row 0 frame=[0.000000 0.000000 320.000000 30.000000] cvframe=[0.000000 0.000000 320.000000 29.000000]
Here I am Row 1 frame=[0.000000 30.000000 320.000000 30.000000] cvframe=[0.000000 0.000000 320.000000 29.000000]

是否预期每个单元有 2 个调用,还是我做错了什么?

最佳答案

我的猜测是 UITableView 将单元格的高度调整了一个像素,以便为绘制分界线腾出空间。在 UITableView 为单元格设置新框架后,您的 layoutSubviews 方法再次被调用。

关于ios - layoutSubviews 在 UITableViewCell 上调用了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11547100/

相关文章:

ios - 如何使用 Swift 3 在默认 ios APP 中打开文档 URL?

objective-c - If-Else 语句被翻转

ios - 如何为我的 ViewModel 编写好的测试? (RxSwift)

objective-c - 根据计时器提示 AVAudioPlayer 播放

ios - Xcode 7.3.1 上的 SwiftLint 集成,并在 .yml 文件配置的 --config 命令上出错

ios - NSDateformatter 不提供正确的日期 swift

ios - UITableView 中所有级别的项目的多级类别

ios - 使用 AVAsset/AVCaptureSession 时,方形视频方向不会从横向变为纵向

ios - 在多个 Storyboard环境中放松 segue

iOS 构建因 IOException 而失败