Is it possible to use AutoLayout with UITableView's tableHeaderView?

前端 未结 29 1360
醉梦人生
醉梦人生 2020-11-28 19:51

Since I discovered AutoLayout I use it everywhere, now I\'m trying to use it with a tableHeaderView.

I made a subclass of

29条回答
  •  眼角桃花
    2020-11-28 20:38

    For most cases the best solution is simply not to fight the framework and embrace autoresizing masks:

    // embrace autoresizing masks and let the framework add the constraints for you
    headerView.translatesAutoresizingMaskIntoConstraints = true
    headerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    
    // figure out what's the best size based on the table view width
    let width = self.tableView.frame.width
    let targetSize = headerView.systemLayoutSizeFitting(CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
    headerView.frame.size = targetSize
    self.tableView.tableHeaderView = headerView
    

    By using autoresizing masks you're telling the framework how your view should change its size when the superview changes its size. But this change is based on the initial frame you've set.

提交回复
热议问题