【问题标题】:Change color of text inside quotations更改引号内文本的颜色
【发布时间】:2016-08-31 23:53:00
【问题描述】:
NSString *message = @"This part: \"Is in quotations\"";

我想知道是否可以将引号内的NSString 部分涂成不同的颜色?我理解这个例子:Is it possible to change color of single word in UITextView and UITextField,但由于我有多个斜杠,所以不确定如何将其转换为我的示例。

【问题讨论】:

  • 使用NSAttributedString,先获取引号之间的所有文本范围,然后应用到NSForegroundColorAttributeName

标签: ios objective-c nsstring uitextview


【解决方案1】:

我写了一个 xcode 游乐场示例(因为我很懒,所以很快),它将为引号内的任何内容着色

var s = "this is a string with \"quotations\" that has multiple \"quotations\" blah blah"

var split:[String] = s.componentsSeparatedByString("\"")

var att:NSMutableAttributedString = NSMutableAttributedString()

for i in 0..<split.count {

    var temp:NSMutableAttributedString

    if((i+1)%2 == 0){ //every even index is something between quotations because of how we split
        temp = NSMutableAttributedString(string: "\"" + split[i] + "\"")
        temp.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location: 0, length: temp.string.characters.count))
    }
    else {
        temp = NSMutableAttributedString(string: split[i])
        temp.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSRange(location: 0, length: temp.string.characters.count))
    }

    att.appendAttributedString(temp)

}

结果:

我相信它会很容易根据您的需要重新调整用途(并用于 Obj-c),或者可以在您自己的操场上使用它

【讨论】:

    猜你喜欢
    • 2013-04-22
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    相关资源
    最近更新 更多