我有一个 NSMutatableString:
var string: String = "Due in %@ (%@) $%@.\nOverdue! Please pay now %@"
attributedText = NSMutableAttributedString(string: string, attributes: attributes)
如何计算单词的长度和起始索引Overdue
快点?
到目前为止我已经尝试过:
let startIndex = attributedText.string.rangeOfString("Overdue")
let range = startIndex..<attributedText.string.finishIndex
// Access the substring.
let substring = value[range]
print(substring)
但这不起作用。
您应该首先生成结果字符串:
let string = String(format: "Due in %@ (%@) $%@.\nOverdue! Please pay now %@", "some date", "something", "15", "some date")
然后使用.disTanceTo
获取索引之间的距离;
if let range = string.rangeOfString("Overdue") {
let start = string.startIndex.distanceTo(range.startIndex)
let length = range.startIndex.distanceTo(string.endIndex)
let wordToEndRange = NSRange(location: start, length: length)
// This is the range you need
attributedText.addAttribute(NSForegroundColorAttributeName,
value: UIColor.blueColor(), range: wordToEndRange)
}
请注意NSRange
如果字符串包含表情符号或其他 Unicode 字符,则无法正常工作,因此上述解决方案可能无法在这种情况下正常工作。
请查看以下 SO 答案,以获得更好的解决方案,该解决方案也涵盖了这种情况:
- https://stackoverflow.com/a/27041376/793428 https://stackoverflow.com/a/27041376/793428
- https://stackoverflow.com/a/27880748/793428 https://stackoverflow.com/a/27880748/793428
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)