2017-07-17 44 views
0

我正在使用自動佈局。如何根據UITextView動態調整xib的大小

  • 我正在從xib加載UIView
  • UITextView之外的所有元素都有靜態大小。
  • 我已禁用UITextView上的滾動
  • UITextView在ViewDidLoad()上填充有不同大小的文本。例如,它可以是1行或7行。

我加載這個UIView的以下方法:

fileprivate func setTableHeaderView() { 
    guard let _headerView = UINib(nibName: "TableHeaderView", 
           bundle: nil).instantiate(withOwner: self, options: nil)[0] as? UIView else { return } 

    tableView.tableHeaderView = UIView(frame: 
     CGRect(x: 0, y: 0, width: tableView.frame.width, height: _headerView.frame.size.height)) 

    configureViewController() // here I set the text for UITextView 
    tableView.tableHeaderView?.addSubview(_headerView) 
} 

當我之前和之後layoutSubviews加載此UIView高度總是相同的。實際上,尺寸總是等於在XCode的Size Inspector中設置的xib的初始尺寸。

我想UITextView來適應文本大小,並有不同的xib UIView大小,這取決於UITextView +所有其他元素+約束的大小。

我試過不同的方法來實現這一點,但沒有人沒有幫助。我試過什麼:

  • 設置限制以不同的方式
  • 強行調用layoutSubviews(),並檢查的大小導致的UIView
  • 與viewDidLayoutSubviews
  • translatesAutoresizingMaskIntoConstraints = true後檢查的UIView的大小autoresizingMask = .flexibleHeight

是否有可能以這種方式實現這個想法?

+0

你需要一個UITextView?你需要有用戶輸入嗎?如果不是這樣,你最好使用UILabel。 – Fogmeister

+0

@Fogmeister不,我不需要確切的UITextView,你認爲UILabel將從xib調整大小幫助UIView? – Danny

+0

UITextView被設計爲當它包含的文本太大時滾動。文本視圖的大小與它內部文本的大小無關。使用UI標籤,標籤的固有尺寸是文本的大小,它應該調整視圖的大小。 – Fogmeister

回答

1

嘗試重寫viewDidLayoutSubviewsMethod

override func viewDidLayoutSubviews() { 
    super.viewDidLayoutSubviews() 

    // Dynamic sizing for the header view 
    if let headerView = tableView.tableHeaderView { 
     let height = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height 
     var headerFrame = headerView.frame 

     // If we don't have this check, viewDidLayoutSubviews() will get 
     // repeatedly, causing the app to hang. 
     if height != headerFrame.size.height { 
      headerFrame.size.height = height 
      headerView.frame = headerFrame 
      tableView.tableHeaderView = headerView 
     } 
    } 
} 
相關問題