如何获取文本视图中动态更改文本的内容高度?

时间:2018-06-25 12:27:32

标签: 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)

为什么没有达到TextView的内容高度? 希望你理解我的问题。 在此先感谢

3 个答案:

答案 0 :(得分:0)

使用此方法获取高度-

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
}

答案 1 :(得分:0)

在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)

//估计是高度

上面第一个方法,第二个方法将在编辑中 第二种方法是

    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中运行

答案 2 :(得分:0)

您只需在下面的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)
}

希望它能对您有所帮助

谢谢。

相关问题