【问题标题】:When I paste text, it can't get height of text当我粘贴文本时,它无法获得文本的高度
【发布时间】:2017-03-31 12:05:17
【问题描述】:

当我粘贴文本时,我得到了错误的文本高度。这不算。我只能得到第一行的高度。但是,如果我单击返回键,每一行文本都像“Software\nis\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")

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

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

【问题讨论】:

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

标签: ios swift xcode string text


【解决方案1】:

把你的代码放进去

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

【讨论】:

  • 感谢您的回答。第一个代码是相同的结果。这意味着当我粘贴文本时改变高度。第二个代码更改了值,但与正确高度相比,它的高度不同:(
猜你喜欢
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2017-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多