【问题标题】:Kern Attribute cause Performance slow issue in UITextviewKern 属性导致 UITextview 中的性能缓慢问题
【发布时间】:2021-06-19 08:25:57
【问题描述】:

我想在用户输入时设置每个字符的宽度。我使用带有键 .Kern 的 NSAttributeString 效果很好,但是当文本长度大于 1000+ 时,我触摸屏幕以将光标位置放在第一行前面并输入导致性能问题的新字符,太慢和滞后。

// Initialize once and reuse every time
lazy var paragraphStyle: NSMutableParagraphStyle = {
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = .byWordWrapping
    paragraphStyle.alignment = .left
    return paragraphStyle
}()

// Initialize once and reuse every time    
lazy var alignTextAttributes: [NSAttributedString.Key: Any] = {
    return [
        .kern : 30,
        .paragraphStyle : paragraphStyle,
        .foregroundColor : UIColor.black,
    ]
}()
    
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    // If I want to set each characters with different kern values, how can I do that?
    alignTextAttributes[.kern] = textView.text.count.isMultiple(of: 2) ? 30 : 10

    // This is the key part
    textView.typingAttributes = alignTextAttributes

    // Allow system to control typing
    return true
}

【问题讨论】:

  • 对我来说这听起来像是一个设计问题。
  • @ElTomato 你是什么意思?

标签: ios swift text attributes uitextview


【解决方案1】:

这是你可以尝试的 -

// 4 (or 6 or 8) spaces (depending on font size)
let padding: String = "   "

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    
    var cursorLocation = textView.selectedRange.location
    if text.isEmpty {
        let deleteRange = NSRange(
            location: max(0, range.location - padding.count), 
            length: range.length + padding.count
        )
        textView.textStorage.replaceCharacters(in: deleteRange, with: text)
        cursorLocation -= deleteRange.length
    } 
    else {
        let insertRange = NSRange(
            location: range.location, 
            length: range.length + padding.count
        )
        textView.textStorage.replaceCharacters(in: insertRange, with: text.appending(padding))
        cursorLocation += insertRange.length
    }
    textView.selectedRange.location = cursorLocation
    
    return false
}

【讨论】:

  • 谢谢,但由于某种原因,我无法添加填充,并在此方法中设置 textview 光标位置,这会导致性能问题。我想你在我之前的问题中已经知道了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-20
  • 1970-01-01
  • 1970-01-01
  • 2011-10-09
  • 2019-05-04
  • 1970-01-01
  • 2013-07-04
相关资源
最近更新 更多