下面是相关的实例方法FooTableViewController
。
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
let textView = UITextView(frame: CGRect.zero, textContainer: nil)
textView.editable = false
textView.font = .systemFontOfSize(17)
textView.scrollEnabled = false
textView.scrollsToTop = false
textView.text = "Random long string"
textView.textContainerInset = UIEdgeInsets(top: 15, left: 12, bottom: 25, right: 12)
tableView.tableHeaderView = textView
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateTableHeaderViewHeightForWidth(view.frame.width)
}
// MARK: - UIContentContainer
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
coordinator.animateAlongsideTransition({ _ in self.updateTableHeaderViewHeightForWidth(size.width) }, completion: nil)
}
// MARK: - Helpers
func updateTableHeaderViewHeightForWidth(width: CGFloat) {
let textView = tableView.tableHeaderView!
let oldHeight = textView.frame.height
let newHeight = textView.sizeThatFits(CGSize(width: width, height: CGFloat.max)).height
textView.frame.size.height = newHeight
tableView.contentSize.height += newHeight - oldHeight
}