【问题标题】:NSAttributedString not working for UILabelNSAttributedString 不适用于 UILabel
【发布时间】:2017-09-15 15:07:55
【问题描述】:

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

我想要做的就是在 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)

【问题讨论】:

  • 您能否检查cell.titleLabel.font 有时返回的值不是粗体字体(每次只打印baseFont)?
  • 我认为你需要传入 cell.titleLabel.attributedText = artist.displayName.emptyIfNil.boldenOccurrences(of: source.currentSearchTerm, baseFont: cell.titleLabel.font, textColor: cell.titleLabel.textColor) 静态 UIFont 值作为基本字体,并且应该可以工作
  • 在 Playground 上测试过,但 myLabel.font = systemFontmyLabel.attributedText = someAttributedStringWithABoldFontForTheWholeRangeNameFontBold; 然后myLabel.font == BoldFont。显然,aLabel.fontaLabel.color 仅适用于 aLabel.text。请勿与aLabel.attributedText 混合使用。我不确定带有属性文本返回的字体是否会返回第一个字符的字体,但这不会让我感到惊讶。而且由于单元格被重复使用,并且在某一时刻,粗体范围包括第一个字符......

标签: ios swift uilabel nsattributedstring


【解决方案1】:

您的主要问题是单元格重用,也许当一个单元格被重用时,将您的字体保持为粗体,这就是您遇到此问题的原因,您可以在您的单元格中解决此问题prepareForReuse() 可以添加的方法

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

【讨论】:

  • 你这个忍者!这绝对是解决办法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多