Using autolayout in a tableHeaderView

前端 未结 8 2146
谎友^
谎友^ 2020-12-01 06:03

I have a UIView subclass that contains a multi-line UILabel. This view uses autolayout.

8条回答
  •  旧时难觅i
    2020-12-01 06:25

    This should do the trick for a headerView or a footerView for the UITableView using AutoLayout.

    extension UITableView {
    
      var tableHeaderViewWithAutolayout: UIView? {
        set (view) {
          tableHeaderView = view
          if let view = view {
            lowerPriorities(view)
            view.frameSize = view.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
            tableHeaderView = view
          }
        }
        get {
          return tableHeaderView
        }
      }
    
      var tableFooterViewWithAutolayout: UIView? {
        set (view) {
          tableFooterView = view
          if let view = view {
            lowerPriorities(view)
            view.frameSize = view.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
            tableFooterView = view
          }
        }
        get {
          return tableFooterView
        }
      }
    
      fileprivate func lowerPriorities(_ view: UIView) {
        for cons in view.constraints {
          if cons.priority.rawValue == 1000 {
            cons.priority = UILayoutPriority(rawValue: 999)
          }
          for v in view.subviews {
            lowerPriorities(v)
          }
        }
      }
    }
    

提交回复
热议问题