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

标题: ios - 如何在表格 View 中正确设置动态标题 View ? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:38
标题: ios - 如何在表格 View 中正确设置动态标题 View ?

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

我一直在查看一些帖子,例如 this one ,但我尝试过的解决方案对我不起作用。当我更改标签中的文本时,我的标题 View 的高度没有更新。

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

  1. tableView(_:viewForHeaderInSection 中将标题 View 作为 UIView 的子类提供与将其作为UITableViewHeaderFooterView 并将其注册到表格 View ?

  2. header View 中的 subview 需要哪些约束才能拥有动态高度?

  3. 应该如何动态更新header view的高度?



Best Answer-推荐答案


您可能想要使用如下功能。调整属性以适合您用于标签的字体和字体大小:

func handleEstimatedFrameForText(_ text: String) -> CGRect {
    let size = CGSize(width: 200, height: 1000)
    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
    return NSString(string: text).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font: UIFont(name: "AvenirNext-Medium", size: 16) as Any], context: nil)
}

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

在设置标题大小的方法中

 var height: CGFloat = 0
    let headerMessage = messages[indexPath.item]
    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 */
    }

您可能需要向 self.handleEstimatedFrameForText(labelText).height + headerImageViewHeight 添加额外的几个像素,因为某些字体需要额外的 12 个像素左右才能在所有设备上工作。反复试验。

关于ios - 如何在表格 View 中正确设置动态标题 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48369292/






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