我環顧四周,無法找到確切的問題,儘管存在幾個類似標題的問題。NSAttributedString對UILabel不起作用
我想要做的就是在UILabel上有一些匹配的文本以BOLD繪製。我在搜索對象時使用它,它應該「增強」搜索項。爲此,我寫了下面的代碼:
extension String {
func boldenOccurrences(of searchTerm: String?, baseFont: UIFont, textColor: UIColor) -> NSAttributedString {
let defaultAttributes: [String : Any] = [NSForegroundColorAttributeName : textColor,
NSFontAttributeName: baseFont]
let result = NSMutableAttributedString(string: self, attributes: defaultAttributes)
guard let searchTerm = searchTerm else {
return result
}
guard searchTerm.characters.count > 0 else {
return result
}
// Ranges. Crash course:
//let testString = "Holy Smokes!"
//let range = testString.startIndex ..< testString.endIndex
//let substring = testString.substring(with: range) // is the same as testString
var searchRange = self.startIndex ..< self.endIndex //whole string
var foundRange: Range<String.Index>!
let boldFont = UIFont(descriptor: baseFont.fontDescriptor.withSymbolicTraits(.traitBold)!, size: baseFont.pointSize)
repeat {
foundRange = self.range(of: searchTerm, options: .caseInsensitive , range: searchRange)
if let found = foundRange {
// now we have to do some stupid stuff to make Range compatible with NSRange
let rangeStartIndex = found.lowerBound
let rangeEndIndex = found.upperBound
let start = self.distance(from: self.startIndex, to: rangeStartIndex)
let length = self.distance(from: rangeStartIndex, to: rangeEndIndex)
log.info("Bolden Text: \(searchTerm) in \(self), range: \(start), \(length)")
let nsRange = NSMakeRange(start, length)
result.setAttributes([NSForegroundColorAttributeName : textColor,
NSFontAttributeName: boldFont], range: nsRange)
searchRange = found.upperBound ..< self.endIndex
}
} while foundRange != nil
return result
}
}
一切都看起來很好。日誌聲明吐出了我期望的東西,這一切都很好。但是,在UILabel上繪製時,有時整個字符串會設置爲粗體,而我不明白這是如何發生的。代碼中沒有任何內容表明這應該發生。
我設置在一個典型的UITableCell配置方法這種上述方法的結果(即tableView(cellForRowAt indexPath:....)
)
cell.titleLabel.attributedText = artist.displayName.emptyIfNil.boldenOccurrences(of: source.currentSearchTerm, baseFont: cell.titleLabel.font, textColor: cell.titleLabel.textColor)
你能檢查有時'cell.titleLabel.font'返回的值是不是一個大膽v ersion字體(每次只打印'baseFont')? – Larme
我認爲你需要傳遞'cell.titleLabel.attributedText = artist.displayName.emptyIfNil.boldenOccurrences(of:source.currentSearchTerm,baseFont:cell.titleLabel.font,textColor:cell.titleLabel.textColor)'static UIFont value as base字體,並且應該工作 –
在Playground上測試過,但'myLabel.font = systemFont'。 'myLabel.attributedText = someAttributedStringWithABoldFontForTheWholeRangeNameFontBold;'然後'myLabel.font == BoldFont'。顯然,'aLabel.font','aLabel.color'只適用於'aLabel.text'。不要與'aLabel.attributedText'混合使用。我不確定使用歸屬文本返回的字體是否會返回第一個字符的字體,但它不會讓我感到驚訝。而且由於細胞被重複使用,並且在一個大膽的範圍包括第一個字符... – Larme