2017-03-31 50 views
0

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

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

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

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

+0

@returntrue是什么意思..?我把下面的代码放在 –

回答

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)) 
} 
+0

谢谢你的回答。第一个代码是相同的结果。这意味着当我粘贴文本时更改高度。第二个代码是更改值,但它是不同的高度比正确的高度:( –

0

试试这个

extension NSAttributedString { 

    func height(withWidth: CGFloat) -> CGFloat { 
     let maxSize = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) 
     let actualSize = boundingRect(with: maxSize, options: [.usesLineFragmentOrigin], context: nil) 
     return actualSize.height 
    } 

} 

extension String { 

    func height(withWidth: CGFloat, font: UIFont) -> CGFloat { 
     let maxSize = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) 
     let actualSize = self.boundingRect(with: maxSize, options: [.usesLineFragmentOrigin], attributes: [NSFontAttributeName: font], context: nil) 
     return actualSize.height 
    } 
} 


// string Height 
let height = str.height(withWidth: 230, font: UIFont.systemFont(ofSize: 17)) 

// attributed string height 
let height = attributedStr.height(withWidth: 230)