菜鸟教程小白 发表于 2022-12-11 19:38:18

ios - 如何在表格 View 中正确设置动态标题 View ?


                                            <p><p>我需要一个部分的标题 View 是一个 <code>UIImageView</code> 和一个 <code>UILabel</code> 在它下面。 ImageView 的高度在创建后不会改变,但标签中的文本可能会由于某些用户操作而改变。我需要动态更新整个标题 View 的高度(使用 AutoLayout,而不是更改框架)。</p>

<p>我一直在查看一些帖子,例如 <a href="https://stackoverflow.com/questions/34661793/setting-tableheaderview-height-dynamically" rel="noreferrer noopener nofollow">this one</a> ,但我尝试过的解决方案对我不起作用。当我更改标签中的文本时,我的标题 View 的高度没有更新。</p>

<p>也许我需要从一开始就了解它是如何工作的。首先,我想明确一点:</p>

<ol>
<li><p>在 <code>tableView(_:viewForHeaderInSection:)</code> 中将标题 View 作为 <code>UIView</code> 的子类提供与将其作为<code>UITableViewHeaderFooterView</code> 并将其注册到表格 View ?</p></li>
<li><p>header View 中的 subview 需要哪些约束才能拥有动态高度?</p></li>
<li><p>应该如何动态更新header view的高度?</p></li>
</ol></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您可能想要使用如下功能。调整属性以适合您用于标签的字体和字体大小:</p>

<pre><code>func handleEstimatedFrameForText(_ text: String) -&gt; CGRect {
    let size = CGSize(width: 200, height: 1000)
    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
    return NSString(string: text).boundingRect(with: size, options: options, attributes: , context: nil)
}
</code></pre>

<p>当您使用该方法设置标题的大小时,您希望使用此函数来获取 <code>UILabel</code> 的高度 AFTER text has been added in and then add on and kind of内边距、<code>UIImageView</code> 高度等</p>

<p><strong>在设置标题大小的方法中</strong></p>

<pre><code> var height: CGFloat = 0
    let headerMessage = messages
    if let labelText = headerMessage.text {
      let headerImageViewHeight: CGFloat = 80 /* ADD IN YOUR UIIMAGEVIEW HEIGHT */
      height = self.handleEstimatedFrameForText(labelText).height + headerImageViewHeight
      return CGSize(width: view.frame.width, height: height)
    } else {
      return CGSize(width: view.frame.width, height: 200) /* DEFAULT SIZE */
    }
</code></pre>

<p>您可能需要向 <code>self.handleEstimatedFrameForText(labelText).height + headerImageViewHeight</code> 添加额外的几个像素,因为某些字体需要额外的 12 个像素左右才能在所有设备上工作。反复试验。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何在表格 View 中正确设置动态标题 View ?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/48369292/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/48369292/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何在表格 View 中正确设置动态标题 View ?