OGeek|极客世界-中国程序员成长平台

标题: iphone - 带有 Storyboard原型(prototype)的 UITableViewCell subview 的动态大小 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 20:05
标题: iphone - 带有 Storyboard原型(prototype)的 UITableViewCell subview 的动态大小

我正在使用 Storyboard 将其中一个原型(prototype)单元定义为“自定义”并添加一个 UITextField。它的左侧有一个标签(带有静态文本)。它有点像“正确的细节”单元格类型,只是正确的部分是可编辑的。

有没有办法经济地调整文本字段的大小,使其从文本标签的末尾到达右边缘?左边的文本标签应该足够大以显示它的文本。

我知道 sizeToFitsizeWithFont:constrainedToSize:,但是调整 subview 的大小似乎相当麻烦,并且必须在每次回收单元格时重复。

有没有办法使用 UIViewautoresizingMask,也许通过在 IB/storyboard 中指定?



Best Answer-推荐答案


我觉得我在上一个问题上让你失望了,所以这里需要更多的努力。

您可以尝试以下方法。这只是一个示例项目,可以让您大致了解一下,但效果很好。

我创建了一个带有单个 TableView Controller 的空项目。这具有硬编码的部分 (1) 和行 (10)。我有一个 Basic 类型的原型(prototype)单元。您可以将任何您喜欢的 View 设置为附件 View ,因此我使用了一个文本字段。因此,所有的魔法都发生在 cellForRowAtIndexPath 中:

- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier"Cell"];

    if (!cell.accessoryView)
    {
        UITextField *accessory = [[UITextField alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 30.0)];
        accessory.borderStyle = UITextBorderStyleLine; // Just so you can see the effect
        cell.accessoryView = accessory;
    }

    NSMutableString *text = [NSMutableString stringWithFormat"A"];

    for (int i = 0; i < indexPath.row; i++) {
        [text appendFormat"A"]; // Just to illustrate different sizes
    }

    cell.textLabel.text = text;

    CGSize labelSize = [cell.textLabel.text sizeWithFont:cell.textLabel.font];
    CGRect accessoryFrame = cell.accessoryView.frame;

    accessoryFrame.size.width = cell.bounds.size.width - labelSize.width - 40; 
    // 40 is a magic number to prevent overlaps, you could be cleverer here
    // You'd also want to restrict to some minimum width.
    cell.accessoryView.frame = accessoryFrame;

    return cell;
}

要点:

这会产生以下输出:

enter image description here

关于iphone - 带有 Storyboard原型(prototype)的 UITableViewCell subview 的动态大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9998226/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4