ios - 尝试为所有出现的 TextView 字符串着色

标签 ios swift uitextview swift2

我正在尝试为 textview 字符串的所有出现(不仅仅是第一次出现)着色,但是当我进入循环时,我得到一个无法调用 rangeOfString 参数。

我查看了关于 Swift 2 的 rangeOfString:options:range 文档,它看起来非常相似。我不太确定自己做错了什么。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!

    func textView(textView: UITextView){

        if textView == self.textView {

            let nsString = textView.text as NSString
            let stringLength = textView.text.characters.count

            var range = NSRange(location: 0, length: textView.text.characters.count)

            let searchString = textView.text

            let text = NSMutableAttributedString(string: textView.text)
            text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, stringLength))

            textView.attributedText = text

            while(range.location != NSNotFound) {

                range = (textView.text as NSString).rangeOfString(searchString, options: NSStringCompareOptions, range: range)

                text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: nsString.rangeOfString("hello"))
            }
        }   
    }
}

最佳答案

您似乎在尝试突出显示搜索栏中的用户输入。我是这样做的:

func highlightedText(text: NSString, inText: NSString, var withColor: UIColor?) -> NSMutableAttributedString {
    var attributedString = NSMutableAttributedString(string:inText as String)
    let range = (inText.lowercaseString as NSString).rangeOfString(text.lowercaseString as String)
    if withColor == nil {
        if let color = globalTint() {
            withColor = color
        } else {
            withColor = UIColor.redColor()
        }
    }
    attributedString.addAttribute(NSForegroundColorAttributeName, value: withColor! , range: range)
    return attributedString
}
...
textView.attributedText = highlightedText("string", inText: titleText, color: nil)

关于ios - 尝试为所有出现的 TextView 字符串着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32519494/

相关文章:

ios - 半透明为 false 时 UIToolBar 上的 Bar Tint

iOS 通用链接 : Do I have to publish my app in order to test Universal Link?

ios - 应用程序将进入后台并进入前台,出现黑屏

ios - 如何在 Xcode 7 b6 上保存为 Adhoc?

ios - 在 Cocos2d v3 iOS 中按住第一次触摸时检测第二次触摸

ios - 如果过滤器返回 nil,我如何不返回空结果?

ios - 如何使空的 UITextView 像 iOS 上的 Notes 一样可滚动?

ios - 光标消失在UITextView中的键盘下

ios - 直到隐藏键盘,按钮才按下

ios - TableView ContentInset 不缩小单元格宽度/向 TableView 内容添加水平填充