我试图调整我的表格视图中的一个单元格的高度。我正在调整单元格的“大小检查器”内的“行高”设置的大小。当我在我的iPhone上运行应用程序时,单元格的默认大小设置自表格视图中的“行大小”。

如果我改变了表格视图的“行大小”,那么所有单元格的大小都会改变。我不想这样做,因为我只想为一个单元格自定义大小。我已经看到了很多关于这个问题的程序化解决方案的帖子,但如果可能的话,我更喜欢通过故事板来实现。


当前回答

在XCode 9上使用Swift 4时也出现了同样的问题。

为单元格内的UI元素添加自动布局,自定义单元格行高将按照指定的方式工作。

其他回答

如果你想设置一个静态行高,你可以这样做:

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

你可以从故事板中获得UITableviewCell的高度(在UITableviewController -静态单元格中)。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   CGFloat height = [super tableView:tableView heightForRowAtIndexPath:indexPath];

    return height;
}

我已经构建了各种答案/注释提示的代码,以便这适用于使用原型单元格的故事板。

这段代码:

不需要单元格高度设置在任何地方除了明显的地方在故事板 出于性能原因缓存高度 使用公共函数获取索引路径的单元格标识符,以避免重复逻辑

感谢Answerbot, Brennan和lensovet。

- (NSString *)cellIdentifierForIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = nil;

    switch (indexPath.section)
    {
        case 0:
            cellIdentifier = @"ArtworkCell";
            break;
         <... and so on ...>
    }

    return cellIdentifier;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [self cellIdentifierForIndexPath:indexPath];
    static NSMutableDictionary *heightCache;
    if (!heightCache)
        heightCache = [[NSMutableDictionary alloc] init];
    NSNumber *cachedHeight = heightCache[cellIdentifier];
    if (cachedHeight)
        return cachedHeight.floatValue;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    CGFloat height = cell.bounds.size.height;
    heightCache[cellIdentifier] = @(height);
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [self cellIdentifierForIndexPath:indexPath];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    <... configure cell as usual...>

在动态单元格上,UITableView上设置的rowHeight总是覆盖单个单元格的rowHeight。

但是在静态单元格上,在单个单元格上设置rowHeight可以覆盖UITableView的。

不确定这是否是一个漏洞,苹果可能是故意这么做的?

在XCode 9上使用Swift 4时也出现了同样的问题。

为单元格内的UI元素添加自动布局,自定义单元格行高将按照指定的方式工作。