Ios NSAttributedString不适用于UILabel

Ios NSAttributedString不适用于UILabel,ios,swift,uilabel,nsattributedstring,Ios,Swift,Uilabel,Nsattributedstring,我环顾四周,没有找到这个确切的问题,尽管有一些问题的标题类似 我想做的就是在UILabel上用粗体绘制一些匹配的文本。我在搜索对象时使用它,它应该“加粗”搜索词。为此,我编写了以下代码: extension String { func boldenOccurrences(of searchTerm: String?, baseFont: UIFont, textColor: UIColor) -> NSAttributedString { let defaultAttrib

我环顾四周,没有找到这个确切的问题,尽管有一些问题的标题类似

我想做的就是在UILabel上用粗体绘制一些匹配的文本。我在搜索对象时使用它,它应该“加粗”搜索词。为此,我编写了以下代码:

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

  }
}
扩展字符串{
func boldenOccurrences(搜索词:String?、baseFont:UIFont、textColor:UIColor的名称)->nsAttribute字符串{
让defaultAttributes:[String:Any]=[NSForegroundColorAttributeName:textColor,
NSFontAttributeName:baseFont]
let result=nsmutableAttributeString(字符串:self,属性:defaultAttributes)
guard let searchTerm=searchTerm else{
返回结果
}
guard searchTerm.characters.count>0其他{
返回结果
}
//范围.速成班:
//让testString=“神圣的烟雾!”
//让range=testString.startIndex..
一切“看起来”都很好。日志语句表达了我的期望,一切都很好。然而,当在UILabel上绘制时,有时整个字符串被设置为粗体,我不明白这是怎么发生的。代码中没有任何内容表明应该发生这种情况

我在典型的UITableCell配置方法中设置了上述方法的结果(即
tableView(cellForRowAt indexPath:…)


cell.titleLabel.attributeText=artist.displayName.emptyIfNil.boldenOccurrencess(of:source.currentSearchTerm,baseFont:cell.titleLabel.font,textColor:cell.titleLabel.textColor)
您的主要问题是单元格的重用,可能在重用单元格时将字体保持为字体粗体,这就是您出现此问题的原因,您可以在您可以添加的单元格
prepareforeuse()
方法中解决此问题

override func prepareForReuse() {
        super.prepareForReuse()
        //to fix ipad Error
        self.titleLabel.font = UIFont(name: "YourBaseFont", size: yourFontSize) 
    }

你能检查一下cell.titleLabel.font有时返回的值是否不是粗体版字体(每次只需打印
baseFont
)?我想你需要传入cell.titleLabel.AttributeText=Artister.displayName.emptyIfNil.boldenOccurrences(of:source.currentSearchTerm、baseFont:cell.titleLabel.font、textColor:cell.titleLabel.textColor)
静态UIFont值作为基本字体,应该在操场上测试,但是
myLabel.font=systemFont
myLabel.attributedText=sometributedStringwithaboldFontfortheherangenemafontbold;
然后
myLabel.font==BoldFont
。显然,
aLabel.font
aLabel.color
仅用于
aLabel.text
。不要与
aLabel.attributedText
混用。我不确定带属性文本返回的字体是否会返回第一个字符的字体,但这不会让我感到惊讶。而且由于单元格是重复使用的,而且在某一点上粗体范围包含了第一个字符……你这个忍者!这肯定是修复方法。