【问题标题】:UITextView change text color of specific textUITextView 更改特定文本的文本颜色
【发布时间】:2016-02-02 00:21:20
【问题描述】:

我想更改 UITextView 中与数组索引匹配的特定文本的文本颜色。我可以稍微修改这个answer,但不幸的是每个匹配短语的文本颜色只改变了一次。

var chordsArray = ["Cmaj", "Bbmaj7"]
func getColoredText(textView: UITextView) -> NSMutableAttributedString {
    let text = textView.text
    let string:NSMutableAttributedString = NSMutableAttributedString(string: text)
    let words:[String] = text.componentsSeparatedByString(" ")
    for word in words {
        if (chordsArray.contains(word)) {
            let range:NSRange = (string.string as NSString).rangeOfString(word)
            string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
        }
    }
    chords.attributedText = string
    return string
}

结果

【问题讨论】:

  • NSAttributedString 是您的答案。对要着色的部分使用颜色属性并将其设为一个字符串。将 rest 放在普通的属性字符串中。现在结合两个属性字符串。
  • @NSNoob 不想打扰你,但你能举个例子吗?我很难理解如何将包含的文本和纯文本拆分为两个不同的 NSAttrubttedStrings。
  • 你在编辑textView吗?我能看到下面的键盘吗?因此,我假设您想在用户输入 chords 数组中定义的那些关键字时为文本着色?刚刚注意到键盘所以我假设你真正想要的是我刚才描述的?在数据输入时重新着色?
  • 是的,我是,这是正确的@NSNoob
  • 是的,该函数正在 textdidchange 上调用

标签: swift uitextview swift2.1


【解决方案1】:

抱歉,我刚刚注意到您的消息。这是一个工作示例(在操场上测试):

import UIKit


func apply (string: NSMutableAttributedString, word: String) -> NSMutableAttributedString {
    let range = (string.string as NSString).rangeOfString(word)
    return apply(string, word: word, range: range, last: range)
}

func apply (string: NSMutableAttributedString, word: String, range: NSRange, last: NSRange) -> NSMutableAttributedString {
    if range.location != NSNotFound {
        string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
        let start = last.location + last.length
        let end = string.string.characters.count - start
        let stringRange = NSRange(location: start, length: end)
        let newRange = (string.string as NSString).rangeOfString(word, options: [], range: stringRange)
        apply(string, word: word, range: newRange, last: range)
    }
    return string
}

var chordsArray = ["Cmaj", "Bbmaj7"]
var text = "Cmaj Bbmaj7 I Love Swift Cmaj Bbmaj7 Swift"
var newText = NSMutableAttributedString(string: text)

for word in chordsArray {
    newText = apply(newText, word: word)
}

newText

【讨论】:

  • 我无法让这个示例在 Swift 2/Xcode 7 中工作
  • 应该可以工作,我只是拿了这段代码并按原样使用它。
【解决方案2】:

以防万一,有人在 swift 4 中需要它。这是我从 Xcode 9 操场上得到的 :)。

import UIKit
import PlaygroundSupport
class MyViewController : UIViewController
{
    override func loadView()
    {
        let view = UIView()
        view.backgroundColor = .white

        let textView = UITextView()
        textView.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        textView.text = "@Kam @Jam @Tam @Ham"
        textView.textColor = .black
        view.addSubview(textView)
        self.view = view

        let query = "@"

        if let str = textView.text {
            let text = NSMutableAttributedString(string: str)
            var searchRange = str.startIndex..<str.endIndex
            while let range = str.range(of: query, options: NSString.CompareOptions.caseInsensitive, range: searchRange) {
                text.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.gray, range: NSRange(range, in: str))
                searchRange = range.upperBound..<searchRange.upperBound
            }
            textView.attributedText = text
        }
    }
}
PlaygroundPage.current.liveView = MyViewController()

我认为对于 swift 3,您需要像这样手动将 Range(String.Index) 转换为 NSRange。

 let start = str.distance(from: str.startIndex, to: range.lowerBound)
 let len = str.distance(from: range.lowerBound, to: range.upperBound)
 let nsrange = NSMakeRange(start, len)
 text.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.gray, range: nsrange)

【讨论】:

    【解决方案3】:

    Swift 4.2 和 5

    let string = "* Your receipt photo was not clear or did not capture the entire receipt details. See our tips here.\n* Your receipt is not from an eligible grocery, convenience or club store."
    let attributedString = NSMutableAttributedString.init(string: string)
    let range = (string as NSString).range(of: "See our tips")
    attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: range)
    txtView.attributedText = attributedString
    txtView.isUserInteractionEnabled = true
    txtView.isEditable = false
    

    输出

    【讨论】:

    • 对于代码的 NSAttributedString.Key.foregroundColor 部分有问题的人,请改用 NSForegroundColorAttributeName
    猜你喜欢
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 2013-04-17
    • 2012-06-16
    • 2012-03-13
    • 2017-12-31
    • 1970-01-01
    相关资源
    最近更新 更多