ios - 键入时 TextView 中的 AttributedText

标签 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

}

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

上执行此操作是合适的

(请注意,我的 addAttributedText 方法对其他 TextView 非常有效)

如果我使用它,在输入一个字符时,它会写入 2x 并崩溃。处理将 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

关于ios - 键入时 TextView 中的 AttributedText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36948521/

相关文章:

ios - 在没有 CoreText 的情况下将 UITextView 中的文本环绕在 UIImage 周围

ios - iOS如何在一个巨大的字符串的2个字符串之间找到多个字符串?

ios - 如何在执行某些操作之前管理多个异步任务?

ios - 当混合中有换行符时,UITextView firstRectForRange 不工作

swift - 设置初始值时调用中缺少参数 #1 的参数

macos - 使用 Swift 获取已安装的卷列表?

ios - UITextView 在使用其委托(delegate)检测何时开始编辑 TextView 时不显示键盘

objective-c - 更改应用程序中只有一个 UIViewController 的 UIInterfaceOrientation

ios - 使用 Apple 服务器验证消耗性 IAP 的正确方法是什么?

database - 使用其数据库部署 iPad 应用程序