如何将属性添加到字符串数组?

how to addAttributes to an array of strings?

我在这里遇到了问题。我想 addAttributes 到我从数组中收集的字符串。我该如何从不完整的函数中解决它?

已编辑:代码工作正常,但正如@Larme 所说,通过使用 range,属性文本将仅附加到找到的 first 范围,而不是休息。 例如,如果文本是 Desmond is careless, I am <b>desmond<b> with a <b>car<b>,最终结果将是 Desmond is careless,我对 desmond 有车有任何想法如何找到重复追加的范围索引?

 func find(inText text: String, pattern: String) -> [String]?
    {
        let regex = try! NSRegularExpression(pattern:pattern+"(.*?)"+pattern, options: [])
        var results = [String]()

        regex.enumerateMatches(in: text, options: [], range: NSMakeRange(0, text.utf16.count))
        { result, flags, stop in
            if let r = result?.range(at: 1),
               let range = Range(r, in: text)
            {
                results.append(String(text[range]))
            }
        }
        return results
    }

   let colorAttribute =
        [NSAttributedStringKey.font: Fonts.OpenSansSemibold(isPhoneSE ? 13 :isPhone3 ? 12 : 16),
         NSAttributedStringKey.foregroundColor: Colors.slate] as [NSAttributedStringKey : Any]

    ***EDITED***

    let boldStrArray = find(inText: item.inbox_body, pattern: "<b>") // find the bold text

    let replaceStr = item.inbox_body!.replacingOccurrences(of: "<b>", with: "")

    print(boldStrArray) //["desmond", "car"]
    print(replaceStr)

    let attrStr = NSMutableAttributedString(string: replaceStr, attributes: normalAttribute)

    for b in boldStrArray!
    {
        let range = (replaceStr as! NSMutableString).range(of: b)
        print(range)
        attrStr.setAttributes(colorAttribute, range: range)
        //attrStr.addAttributes(colorAttribute, range: range)
    }

非常感谢任何评论:)

试试这个:

let attrString = NSMutableAttributedString(string: "This is an attributed string")

    let range = attrString.mutableString.range(of: "attributed")

    attrString.setAttributes([:], range: range)

如果 find(inText:pattern:) returns (NS)Range 会更容易(或者更好地吸收 NSTextCheckingResult)。

所以经过一些修改:

func find(inText text: String, pattern: String) -> [NSTextCheckingResult] {
    let regex = try! NSRegularExpression(pattern:pattern+"(.*?)"+pattern, options: []) //There should be a try/catch at least
    return regex.matches(in: text, options: [], range: NSRange.init(location: 0, length: text.utf16.count))
}

我用的是我的"own font & color",因为我没有你的设置。 因为不容易猜到你可以根据你使用的模式使用 range(at: 1),所以我不会使用方法而是将它写在里面。

let initialString = "I am <b>desmond<b> with a <b>car<b>"
let colorAttribute: [NSAttributedStringKey : Any] = [.font: UIFont.boldSystemFont(ofSize: 12),
                                                     .foregroundColor: UIColor.red]

var attrStr = NSMutableAttributedString(string: initialString)
print("BEFORE attrStr: \(attrStr)")
let boldRanges = find(inText: initialString, pattern: "<b>")
boldRanges.reversed().forEach { (aResult) in
    let subTextNSRange = aResult.range(at: 1)
    guard let subTextRange = Range(subTextNSRange, in: attrStr.string) else { return } //This is to "switch" between NSRange & Range
    let replacementString = String(attrStr.string[subTextRange])
    let replacementAttributedString = NSAttributedString(string: replacementString, attributes: colorAttribute)
    attrStr.replaceCharacters(in: aResult.range, with: replacementAttributedString)
}
print("AFTER attrStr: \(attrStr)")

输出:

$> BEFORE attrStr: I am <b>desmond<b> with a <b>car<b>{
}
$> AFTER attrStr: I am {
}desmond{
    NSColor = "sRGB IEC61966-2.1 colorspace 1 0 0 1";
    NSFont = "\".AppleSystemUIFontBold 12.00 pt. P [] (0x60c000051e50) fobj=0x101a36cf0, spc=3.09\"";
} with a {
}car{
    NSColor = "sRGB IEC61966-2.1 colorspace 1 0 0 1";
    NSFont = "\".AppleSystemUIFontBold 12.00 pt. P [] (0x60c000051e50) fobj=0x101a36cf0, spc=3.09\"";
}