【问题标题】:UITextView tableHeaderView Intrinsic HeightUITextView tableHeaderView 固有高度
【发布时间】:2017-01-04 07:56:54
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: uitableview autolayout uitextview autoresizingmask contentsize


    【解决方案1】:

    下面是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-04-12
      • 1970-01-01
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多