UITextView tableHeaderView内在高度

时间:2016-08-27 23:29:11

标签: uitableview autolayout uitextview autoresizingmask contentsize

我以编程方式(没有Story Board或Interface Builder)创建了UITableViewController的自定义子类FooTableViewController

viewDidLoad中,我将tableView.tableHeaderView设置为不可编辑的UITextView,其任意高度为200,其text设置为随机{ {1}}。

当我旋转设备时,String会自动更新其宽度。当我设置UITextView时(如果它确实包含text),如何让它自动更新其高度?

注意:我使用的是不可编辑的text而不是UITextView,因为我希望用户能够选择和复制文字。

1 个答案:

答案 0 :(得分:0)

以下是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
}