菜鸟教程小白 发表于 2022-12-12 20:05:52

iphone - 带有 Storyboard原型(prototype)的 UITableViewCell subview 的动态大小


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

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

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

<p>有没有办法使用 <code>UIView</code> 的 <code>autoresizingMask</code>,也许通过在 IB/storyboard 中指定? </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>我觉得我在上一个问题上让你失望了,所以这里需要更多的努力。 </p>

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

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

<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = ;

    if (!cell.accessoryView)
    {
      UITextField *accessory = [ 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 = ;

    for (int i = 0; i &lt; indexPath.row; i++) {
      ; // Just to illustrate different sizes
    }

    cell.textLabel.text = text;

    CGSize labelSize = ;
    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&#39;d also want to restrict to some minimum width.
    cell.accessoryView.frame = accessoryFrame;

    return cell;
}
</code></pre>

<p>要点:</p>

<ul>
<li>您只需要调整附件 View 的大小。 </li>
<li>文本字段非常基本 - 通常您需要一个为您返回一个的小工厂方法,设置委托(delegate),可能还需要一个工具栏作为带有上一个、下一个和完成按钮的辅助 View </li>
<li>将文本字段中输入的值分配回数据模型是留给读者的练习。</li>
</ul>

<p>这会产生以下输出:</p>

<p> <img src="/image/YTiKP.png" alt="enter image description here"/> </p></p>
                                   
                                                <p style="font-size: 20px;">关于iphone - 带有 Storyboard原型(prototype)的 UITableViewCellsubview 的动态大小,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/9998226/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/9998226/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: iphone - 带有 Storyboard原型(prototype)的 UITableViewCell subview 的动态大小