键入时TextView中的AttributedText



我有一个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
}

我尝试在viewDidLoad中向textView添加带有空文本的attributedString,但这没有帮助。这就是为什么我认为在shouldChangeTextInRange 上这样做是合适的

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

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

这是我试图从上面的链接转换的代码,它可能有错误,但我希望它能帮助你。

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
}

编辑:没有看到在最初的帖子中有Swift的答案,这里有链接:stackoverflow.com/a/35842523/1226963

最新更新