键入时 TextView 中的 AttributedText

AttributedText in TextView while typing

我有一个 textView,我想给它一个属性文本。我尝试在 shouldChangeTextInRange 内实现它,但它在超出索引范围时崩溃。

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { 

   if myTextView {
      textView.attributedText = addAttributedText(1, text: text, fontsize: 13)

      let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
      let numberOfChars = newText.characters.count

      return numberOfChars < 20
   }
   return true
}

 func addAttributedText(spacing:CGFloat, text:String, fontsize: CGFloat) -> NSMutableAttributedString {
    let attributedString = NSMutableAttributedString(string: text, attributes: [NSFontAttributeName:UIFont(
        name: "Font",
        size: fontsize)!])
    attributedString.addAttribute(NSKernAttributeName, value: spacing, range: NSMakeRange(0, text.characters.count))
    return attributedString

}

我尝试将带有空文本的 attributedString 添加到 viewDidLoad 中的 textView,但这没有帮助。这就是为什么我认为在 shouldChangeTextInRange

上这样做是合适的

(请注意,我的 addAttributedText 方法适用于其他文本视图)

如果我使用它,在输入一个字符时,它会写入 2x 并崩溃。处理将 textView 的文本转换为正在键入的属性文本的正确方法是什么。

以上是我尝试从link转换过来的代码,可能有bug,希望能帮到你。

func formatTextInTextView(textView: UITextView) 
{
    textView.scrollEnabled = false
    var selectedRange: NSRange = textView.selectedRange
    var text: String = textView.text!
    // This will give me an attributedString with the base text-style
    var attributedString: NSMutableAttributedString = NSMutableAttributedString(string: text)
    var error: NSError? = nil
    var regex: NSRegularExpression = NSRegularExpression.regularExpressionWithPattern("#(\w+)", options: 0, error: error!)
    var matches: [AnyObject] = regex.matchesInString(text, options: 0, range: NSMakeRange(0, text.length))

    for match: NSTextCheckingResult in matches {
        var matchRange: NSRange = match.rangeAtIndex(0)
        attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: matchRange)
    }
    textView.attributedText = attributedString
    textView.selectedRange = selectedRange
    textView.scrollEnabled = true
}

编辑:在原来的 post 中没有看到 Swift 的答案,这里是 link:whosebug.com/a/35842523/1226963