2017-08-23 28 views
0

我有一個UITextView行事真的很奇怪,爲什麼我試圖用自動佈局來限制它。背景將被放置正確,但文字內容不合適。我試圖創建一個UIView,然後將其添加到UIView,但問題仍然存在。UITextView放置代碼奇怪與自動佈局

這裏是UITextView的和UIView的聲明

let noteTextView: UITextView = 
{ 
    let tv = UITextView() 
    tv.textColor = UIColor.white 
    tv.backgroundColor = UIColor.clear 
    tv.font = UIFont.systemFont(ofSize: 16) 
    tv.isEditable = false 
    tv.isUserInteractionEnabled = true 

    return tv 
}() 

let backgroundView: UIView = 
{ 
    let view = UIView() 
    view.backgroundColor = UIColor.rgb(red: 156, green: 44, blue: 252) 

    return view 
}() 

這裏是限制(使用稱爲錨的擴展名)

view.addSubview(backgroundView) 
    backgroundView.addSubview(noteTextView) 

    backgroundView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 65, paddingLeft: 0, paddingRight: 0, paddingBottom: 0, width: 0, height: 80) 

    noteTextView.anchor(top: backgroundView.topAnchor, left: backgroundView.leftAnchor, bottom: backgroundView.bottomAnchor, right: backgroundView.rightAnchor, paddingTop: 2, paddingLeft: 5, paddingRight: 5, paddingBottom: 2, width: 0, height: 0) 

下面是一個視頻來演示該問題:https://streamable.com/y8v70

注意:當我將UITextView添加到視圖(沒有UIVIew)時,發生了完全相同的事情。

+0

爲什麼你不使用UILabel? – TomCobo

+0

因爲文本可能會很長,並且我不知道在從數據庫中獲取文本時會有多少行。 – Elhoej

回答

1

禁用automaticallyAdjustsScrollViewInsetsviewDidLoad

self.automaticallyAdjustsScrollViewInsets = false 

也嘗試:

textView.textContainerInset = UIEdgeInsetsZero; 
textView.textContainer.lineFragmentPadding = 0; 

願這幫助。

+0

第一種方案奏效!非常感謝! – Elhoej

0

不要爲UIView或UITextView提供靜態高度。

試試這個功能:

func textviewHeight() { 

     let contentSize = self.TextView.sizeThatFits(self.TextView.bounds.size) 
     var frame = self.TextView.frame 
     frame.size.height = contentSize.height 
     self.TextView.frame = frame 

     self.aspectRatioTextView = NSLayoutConstraint(item: self.TextView, attribute: .Height, relatedBy: .Equal, toItem: self.TextView, attribute: .Width, multiplier: TextView.bounds.height/TextView.bounds.width, constant: 1) 
     self.TextView.addConstraint(self.aspectRatioTextView!) 

     self.mainViewHeightConstraint.constant = self.mainViewHeightConstraint.constant + self.TextView.frame.height 
    } 

可能是它可以幫助你!!!!!