@Vijay 对此帖子有一个很好的正确答案。
我通过创建一个接受searchString 和您要修改的字符串的函数来为自己的目的(在搜索结果中加粗文本)稍微修改了这个 -
resultString - 并返回可应用于 UILabel 的 attributedString。
我还检查了lowercaseString 属性,因此无论我在搜索栏中输入什么内容,我的字符串都会匹配字符而不是大小写(此要求可能会有所不同,具体取决于您的用例)。
func boldSearchResult(searchString: String, resultString: String) -> NSMutableAttributedString {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: resultString)
let pattern = searchString.lowercaseString
let range: NSRange = NSMakeRange(0, resultString.characters.count)
let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions())
regex.enumerateMatchesInString(resultString.lowercaseString, options: NSMatchingOptions(), range: range) { (textCheckingResult, matchingFlags, stop) -> Void in
let subRange = textCheckingResult?.range
attributedString.addAttribute(NSFontAttributeName, value: UIFont.customBoldedFontNameWithSize(15.0), range: subRange!)
}
return attributedString
}
注意:我可以使用自定义的粗体字体,但您始终可以使用 UIFont.boldSystemFontOfSize(fontSize: CGFloat) 或类似的东西来获得类似的效果。
然后,只需执行以下操作(一些变体)将结果添加到您的标签:
cell.myCustomLabel.attributedText = boldSearchResult(mySearchText, resultString: textForBolding)