键入时TextView中的AttributedText

时间:2016-04-29 22:38:01

标签: ios swift uitextview nsattributedstring uitextviewdelegate

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

}

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

上进行此操作的原因

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

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

1 个答案:

答案 0 :(得分:1)

以下是我尝试从上面的链接转换的代码,它可能有错误,但我希望它能够帮助您。

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

相关问题