NSAttributedString不适用于UILabel

时间:2017-09-15 15:07:55

标签: ios swift uilabel nsattributedstring

我环顾四周,找不到这个确切的问题,尽管有几个类似标题的问题。

我想要做的就是在BIL中绘制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

  }
}

一切“看起来都很好”。日志语句吐出了我的期望,这一切都很好。但是,当在UILabel上绘制时,有时整个字符串被设置为粗体,我不明白这是怎么回事。代码中没有任何内容表明这应该发生。

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

cell.titleLabel.attributedText = artist.displayName.emptyIfNil.boldenOccurrences(of: source.currentSearchTerm, baseFont: cell.titleLabel.font, textColor: cell.titleLabel.textColor)

1 个答案:

答案 0 :(得分:2)

您的主要问题是单元格重用,可能在重复使用单元格时将字体粗体保留为字体,这就是您遇到此问题的原因,您可以在单元prepareForReuse()方法中解决此问题,您可以添加< / p>

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