好的,所以可能有更简单的方法来做到这一点......
所以,我浏览了 API(比如超级快)并寻找类似 @987654327@ 的东西,它引导我找到String#range(of:options),它允许您向后搜索,嗯,很有趣。
这会返回一个Range<String.Index> ...好的,那我该如何使用它呢?!嗯,也许String#replacingOccurrences(of:with:options:range:)?
所以,打开一个游乐场然后......
var str = "hello world, hello"
let lastIndexOf = str.range(of: "hello", options: .backwards)
str = str.replacingOccurrences(of: "hello", with: "thanks", options: .caseInsensitive, range: lastIndexOf)
str 现在等于 "hello world, thanks"
嗨@MadProgrammer,你的代码是替换最后一个你好词来感谢,对吧?但我的问题是用粗体属性替换 hello,它可能在字符串的开头、中间或结尾。
好的,很明显我们缺少一些上下文...
假设,现在,您使用的是NSAttributedString,它会变得稍微复杂一些
构建字符串本身并不难,弄清楚如何通过属性找到字符串组件,有点困难。
幸运的是,我们有互联网。因此,以下是基于我从中获得的想法:
在尝试解决问题时要记住的重要事项之一是,您很幸运能找到一个解决所有问题的单一答案,相反,您需要分解问题并专注于解决单个元素,并且准备回到起点?
所以,再一次,去操场......
import UIKit
var str = "hello world, "
//let lastIndexOf = str.range(of: "hello", options: .backwards)
//str = str.replacingOccurrences(of: "hello", with: "thanks", options: .caseInsensitive, range: lastIndexOf)
extension UIFont {
var isBold: Bool {
return fontDescriptor.symbolicTraits.contains(.traitBold)
}
var isItalic: Bool {
return fontDescriptor.symbolicTraits.contains(.traitItalic)
}
}
// Just so I can see that the style ;)
let fontSize = CGFloat(24.0)
let boldAttrs = [
NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: fontSize),
NSAttributedString.Key.foregroundColor: UIColor.white // Playground
]
// Playground only
let plainAttrs = [
NSAttributedString.Key.foregroundColor: UIColor.white // Playground
]
let boldText = NSMutableAttributedString(string: "hello", attributes: boldAttrs)
let styledText = NSMutableAttributedString(string: str, attributes: plainAttrs)
let someMoreBoldText = NSMutableAttributedString(string: "not to be replaced", attributes: boldAttrs)
// Attributes can be combined with their appear together ;)
styledText.append(boldText)
styledText.append(NSMutableAttributedString(string: " ", attributes: plainAttrs))
styledText.append(someMoreBoldText)
styledText.append(NSMutableAttributedString(string: " ", attributes: plainAttrs))
styledText.append(boldText)
styledText.enumerateAttribute(NSAttributedString.Key.font, in: NSRange(0..<styledText.length)) { (value, range, stop) in
guard let font = value as? UIFont, font.isBold else {
return;
}
let subText = styledText.attributedSubstring(from: range)
guard subText.string == "hello" else {
return
}
styledText.replaceCharacters(in: range, with: "thanks")
}
styledText
哪些输出...
对我来说重要的是:
- 样式没变
- 仅更改了以粗体显示的单个“hello”值