代码之家  ›  专栏  ›  技术社区  ›  Anters Bear

在uitextview中测量线条的高度

  •  0
  • Anters Bear  · 技术社区  · 6 年前

    我试图测量行的高度,以便在 UITextView . 具体来说,我所说的行是用 \n . 所以一条线实际上可以跨越多条线,这就是我要测量的。我尝试了几种不同的方法,但是,我似乎无法正确计算高度。我目前的方法的另一个缺点是它必须在主同步线程上计算,这不太理想,因为我有很多计算要做。

    示例ui方法

    measurement.font = UIFont(name: "Menlo", size: 16)
    measurement.frame = CGRect(x: 0, y: 0, width: 10000, height: 50)
    
    func heightForString(line: String) -> CGFloat {
        var height : CGFloat = 0
        measurement.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 10000)
        measurement.sizeToFit()
        height = measurement.frame.height
        print(height, lineHeight)
        measurement.frame = CGRect(x: 0, y: 0, width: 10000, height: 50)
        return height
    }
    // Comparing the returned height to measurement.font?.lineHeight and padding shows the results make little sense... :(
    

    打印示例

    应该是1行

    30 18.625

    应该是3行

    43.66666666667 18.625

    1 回复  |  直到 6 年前
        1
  •  1
  •   sohan vanani    6 年前
    func heightForString(line: String) -> CGFloat {
        let textView = UITextView()
        let maxwidth = UIScreen.main.bounds.width
        textView.frame = CGRect(x:0,y: 0,width: maxwidth,height: CGFloat(MAXFLOAT))
        textView.textContainerInset = UIEdgeInsets.zero
        textView.textContainer.lineFragmentPadding = 0
        textView.font = UIFont(name: "Menlo", size: 16)
        textView.text = line
        textView.isScrollEnabled = false
        textView.sizeToFit()
        return textView.frame.size.height
    }