2016-05-30 100 views
5

我在UIStackView裏添加了我的UITextView。UIStackView裏面的UITextView

但我的textview不是Multiline。

自動佈局被示出如下:

enter image description here

由於每個圖像是剛拍攝1行。 textview框架按照圖像顯示爲框架外部。

的UITextView

enter image description here enter image description here

UIStackView

enter image description here

+0

那麼,什麼問題? – Lion

+0

@Lion,它應該用多行顯示嗎? – user2526811

回答

14

的問題是,你有固定的height的UIStackview通過給予頂部底部限制。

  1. 刪除底部約束

    enter image description here

禁用TextView的滾動。

讓您的TextView代表自我和實現textViewDidChange

斯威夫特

func textViewDidChange(_ textView: UITextView) { 
    view.layoutIfNeeded() 
} 

目標C:

-(void)textViewDidChange:(UITextView *)textView { 
    [self.view layoutIfNeeded]; 
} 

確保這個方法被調用。

現在你的stackview應該隨着你的textview增長到多行。

然後你的textview不是多行的原因是因爲你已經固定了高度。所以它永遠不會是多行的。

查看GIF:

enter image description here

+1

非常好!如果你有靜態文本,我發現如果你重寫viewDidLayoutSubviews(),你可以在那裏獲得內容高度並更新高度約束。但是你的回答讓我走上了正確的道路! \t倍率FUNC viewDidLayoutSubviews(){ \t \t super.viewDidLayoutSubviews() \t \t textViewHeightConstraint.constant = textView.contentSize.height \t \t textView.layoutIfNeeded() \t} –

0

最好的解決辦法,我發現這個至今包裹的UITextView在一個UIView,然後設置的UITextView的固定高度的高度錨。

let textView = UITextView() 
let containerView = UIView() 
textView.translatesAutoresizingMaskIntoConstraints = false 
containerView.addSubview(textView) 

textView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true 
textView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true 
textView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true 
textView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true 

textView.heightAnchor.constraint(equalToConstant: 100).isActive = true 
let stackView = UIStackView(arrangedSubviews: [containerView])