【问题标题】:Complex resize of Cells in UITableViewCellUITableViewCell 中单元格的复杂调整大小
【发布时间】:2013-07-15 10:30:44
【问题描述】:

我正在编写一个主要基于 TableView 的通用 iOS 应用程序(iPhone 和 iPad)。每个单元格都有多个文本区域,我需要根据内容调整高度。我在 Storyboard 中定义了所有表格和单元格,我真的很想保持这种状态(以图形方式更容易地使用大小来查看它将是什么)。

问题是我需要大量信息来计算单元格的最终大小(单元格和子视图的故事板高度、标签宽度、字体大小......)。我曾经在我的代码中只有常量,我会在其中手写值但是:

  • 每次更改情节提要都很痛苦
  • 我的标签可以有不同的宽度(不同类型的单元格,iPhone/iPad),我有很多这样的标签,所以在这种情况下,需要跟踪大量常量

我使用那个解决方案:

在单元格中,我设置了一次静态变量以记住大小(它是从情节提要中获取的,这很好):

static float cellDefaultHeight;
static float contactsLabelDefaultHeight;
static float contactsLabelDefaultWidth;
static float contactsLabelFontSize;
-(void) awakeFromNib
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // instantiate static variables with the constants
        cellDefaultHeight = self.contentView.bounds.size.height;

        contactsLabelDefaultHeight = self.contacts.bounds.size.height;
        contactsLabelDefaultWidth = self.contacts.bounds.size.width;
        contactsLabelFontSize = self.contacts.font.pointSize;
    });
}

+ (CGFloat) heightForCellWithData:(NSDictionary *)data
{
    // use constants and data to compute the height
    return height
}

在计算任何单元格大小之前,我必须在表格中实例化一个以设置静态变量:

- (CGFloat)tableView:(UITableView *)tableView 
                 heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // get one instance before any size computation
    // or the constant won't be there
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        static NSString *CellIdentifier = @"identifier";
        [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    });

    return [MyCell heightForCellWithData:theData];
}

感觉太骇人听闻了,我觉得我完全错过了一些东西,但我想不出别的东西。有什么好的方法吗?

谢谢!

【问题讨论】:

  • 根据您所说的原因,这是最好的方法。

标签: iphone ios uitableview


【解决方案1】:

首先,我认为您应该使用自定义单元格来执行此类操作。现在,每次如果您需要更改宽度/高度,您只需要该单元格的边界。关于标签和文本字段的宽度/高度,您可以像(self.textview.bounds)一样,然后您可以根据需要设置偏移量。这不是黑客攻击,而是根据逻辑进行的纯编码,因为每次如果您更改设备,它将相应地采用界限,因此无需记住任何内容。 希望这有效:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 2013-05-26
    相关资源
    最近更新 更多