0

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

viewDidLoad中,我已将其设置为任意高度tableView.tableHeaderView的不可编辑,并将其设置为随机。UITextView200textString

UITextView我旋转设备时,它会自动更新其宽度。text当我设置它(以便它完全包含它)时,如何让它自动更新它的高度text

注意:我使用的是 uneditableUITextView而不是 a UILabel,因为我希望用户能够选择和复制文本。

4

1 回答 1

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
}
于 2016-08-28T01:59:18.580 回答