当我粘贴文本时,它无法获得文本的高度

时间:2017-03-31 12:05:18

标签: ios swift xcode string text

当我粘贴文字时,我的文字高度错误。它不算数。我只能获得第一线的高度。但是,如果我单击返回键,每行文本如“Software \ nis \ nawesome”,它运行良好。这是代码:

<router-outlet></router-outlet>

但是,当我输入一些文字时,我可以得到正确的文字高度。

如何获得正确的文字高度?

1 个答案:

答案 0 :(得分:0)

将您的代码放入

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
       let font = UIFont(name: "HelveticaNeue", size: 18)!
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center
    paragraphStyle.lineSpacing = 8

    let textFontAttributes = [
         NSFontAttributeName: font,
         NSForegroundColorAttributeName: UIColor(red: 0.149, green: 0.149, blue: 0.145, alpha: 1.00),
         NSParagraphStyleAttributeName: paragraphStyle
         ] as [String : Any]

    let string:NSString = NSString(string: self.txtView.text)
    let size:CGSize = string.size(attributes: textFontAttributes)
    print("size.height")
    return true;
 }

您也可以使用

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
      let size = self.textView.sizeThatFits(CGSize(width: width_you_can_afford, height: CGFloat.greatestFiniteMagnitude))
}