【问题标题】:How to make auto resizing header view in tableview swift?如何在tableview swift中自动调整标题视图的大小?
【发布时间】:2021-09-29 10:24:32
【问题描述】:

我刚刚在表格视图中放置了一个视图,该视图包含图像和标签。但是标签内容是动态的,不想裁剪它,而是我想根据需要增加视图的高度。但标题视图也不接受约束。那我能实现吗?问题出现在查找朋友按钮上方的标签上。

【问题讨论】:

    标签: ios swift xcode uitableview


    【解决方案1】:

    TableView 表头高度不会自动刷新,每次其内容发生变化时,您必须自己重新计算高度。高度重新计算和tableview标题刷新可以在'viewDidLayoutSubviews'方法中完成。

    override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
    
            guard let headerView = tableView.tableHeaderView else {
                return
            }
            let size = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
    
            if headerView.frame.size.height != size.height {
                headerView.frame.size.height = size.height
                tableView.tableHeaderView = headerView
                // This only seems to be necessary on iOS 9.
                tableView.layoutIfNeeded()
            }
        }
    

    答案和代码片段是“Variable Height Table View Header”帖子的简短摘要,可在 usyourloaf 访问

    【讨论】:

      【解决方案2】:

      您需要使用文本估计标签高度,并加上图像/按钮高度来计算标题视图的总高度

      func estimatedLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat {
      
          let size = CGSize(width: width, height: 1000)
      
          let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
      
          let attributes = [NSAttributedStringKey.font: font]
      
          let rectangleHeight = String(text).boundingRect(with: size, options: options, attributes: attributes, context: nil).height
      
          return rectangleHeight
      }
      

      这里是估计标题高度的方法:

      func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
          return label size + other size
      }
      

      或者您可以使用自动布局来避免估计高度:

      • 设置标签 numberOfLines = 0
      • 在垂直方向上设置每个单元格之间的垂直填充约束
      • 中返回UITableView.automaticDimension
      func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
         return UITableView.automaticDimension
      }
      

      【讨论】:

      • 但是我会在哪里使用这个功能
      • 你可以使用自动布局,也可以让系统估计高度
      猜你喜欢
      • 2015-08-30
      • 1970-01-01
      • 2014-11-05
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多