Ios 如何在textview中获取动态变化文本的内容高度?
我在Ios 如何在textview中获取动态变化文本的内容高度?,ios,swift,uitextview,Ios,Swift,Uitextview,我在TextView中有一个动态变化的文本。我无法获取TextView的内容高度 这是我试过的 let height = self.tvComment.contentSize.height print("height",height) let contentSizeComment = self.tvComment.sizeThatFits(self.tvComment.bounds.size) print("height",contentSizeComment) 为什么它没有获得TextVi
TextView
中有一个动态变化的文本。我无法获取TextView
的内容高度
这是我试过的
let height = self.tvComment.contentSize.height
print("height",height)
let contentSizeComment = self.tvComment.sizeThatFits(self.tvComment.bounds.size)
print("height",contentSizeComment)
为什么它没有获得TextView
的内容高度?
希望你能理解我的问题。
提前感谢使用此方法获取高度-
func heightForString(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.size.height
}
在textdidchange中,您可以使用此代码,以便在textchange时调整大小
//approxi should be the width of your textview
let approxi = view.frame.width - 90
//size is the max width and height of textview,1000 can be what ever you want
let size = CGSize(width: approxi, height: 1000)
//dont forget to put your font and size
//chey is the text of thetext view
let attributes = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 15)]
let estim = NSString(string: chey).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
//estim是高度
上面是第一个方法,第二个方法是编辑
第二种方法是
func pva() {
//what was the name of my textfield
let fixedwidth = what.frame.size.width - 40
let newsize = what.contentSize.height
self.hrightext.constant = newsize
self.view.layoutIfNeeded()
}
注意:这两个都是在swift4中测试和工作的您只需在以下UITextView委托中编写代码即可:-
func textViewDidChange(_ textView: UITextView!) {
let height = self.tvComment.contentSize.height
print("height",height)
let contentSizeComment = self.tvComment.sizeThatFits(self.tvComment.bounds.size)
print("height",contentSizeComment)
}
我希望它能帮助你
谢谢。在viewDidLayoutSubviews()方法中写下它可能与