-systemLayoutSizeFittingSize: returning incorrect height for tableHeaderView under iOS 8

前端 未结 6 1977
旧时难觅i
旧时难觅i 2021-02-07 00:08

There are numerous threads about correctly sizing a tableHeaderView with auto-layout (one such thread) but they tend to pre-date iOS 8.

I have a situation with numerous

6条回答
  •  南旧
    南旧 (楼主)
    2021-02-07 00:52

    If the header just contains a single label then I use a UILabel extension to find a multiline label height given a width:

    public extension UILabel {
        public class func size(withText text: String, forWidth width: CGFloat) -> CGSize {
            let measurementLabel = UILabel()
            measurementLabel.text = text
            measurementLabel.numberOfLines = 0
            measurementLabel.lineBreakMode = .byWordWrapping
            measurementLabel.translatesAutoresizingMaskIntoConstraints = false
            measurementLabel.widthAnchor.constraint(equalToConstant: width).isActive = true
            let size = measurementLabel.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
            return size
        }
    }
    

    Note: the above is in Swift 3 syntax.

    With the size calculated above you can return the correct height in the UITableViewDelegate method:

    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
    

提交回复
热议问题