如何修复 Swift 中的 UITextView 文本内容位置
How to fix UITextView text content position in Swift
我有 UIView
class 并且在这个 class 中有 UITextView
用作 inputText
在第 2 行到第 5 行的 textViewDidChange
中,使用任何中间件或添加文本,我根据需要添加 UITextView
bounds.size.height
。
问题是,在第 3 行和第 5 行中,第一行文字没有出现。
大致比它自己高一排 space。
并且是从空的底部创建的space,没有滚动。
但是第 4 行的文字有准确的位置
class QuestionCell: UIView, UITextViewDelegate{
var paragraph = UITextView()
func setParagraph(){
let frame = CGRect(x: 50,
y: 0,
width: forground.width-55,
height: forground.height)
paragraph.frame = frame
paragraph.isEditable = true
paragraph.delegate = self
// forground is some UIView in this View
forground.addSubview(paragraph)
}
func textViewDidChange(_ textView: UITextView) {
paragraph.bounds.size.height = paragraph.paragraphHeight
}
}
extension UITextView{
var paragraphHeight: CGFloat{
let fixedWidth = self.width
let newSize = self.sizeThatFits(CGSize.init(width: fixedWidth,
height: CGFloat(MAXFLOAT)))
var newFrame = self.frame
newFrame.size = CGSize.init(width: CGFloat(fmaxf(Float(newSize.width),
Float(fixedWidth))),
height: newSize.height)
return newSize.height
}
}
创建时需要指定:
paragraph.isScrollEnabled = false
创建后,您可以重新设置。
我有 UIView
class 并且在这个 class 中有 UITextView
用作 inputText
在第 2 行到第 5 行的 textViewDidChange
中,使用任何中间件或添加文本,我根据需要添加 UITextView
bounds.size.height
。
问题是,在第 3 行和第 5 行中,第一行文字没有出现。 大致比它自己高一排 space。 并且是从空的底部创建的space,没有滚动。
但是第 4 行的文字有准确的位置
class QuestionCell: UIView, UITextViewDelegate{
var paragraph = UITextView()
func setParagraph(){
let frame = CGRect(x: 50,
y: 0,
width: forground.width-55,
height: forground.height)
paragraph.frame = frame
paragraph.isEditable = true
paragraph.delegate = self
// forground is some UIView in this View
forground.addSubview(paragraph)
}
func textViewDidChange(_ textView: UITextView) {
paragraph.bounds.size.height = paragraph.paragraphHeight
}
}
extension UITextView{
var paragraphHeight: CGFloat{
let fixedWidth = self.width
let newSize = self.sizeThatFits(CGSize.init(width: fixedWidth,
height: CGFloat(MAXFLOAT)))
var newFrame = self.frame
newFrame.size = CGSize.init(width: CGFloat(fmaxf(Float(newSize.width),
Float(fixedWidth))),
height: newSize.height)
return newSize.height
}
}
创建时需要指定:
paragraph.isScrollEnabled = false
创建后,您可以重新设置。