当用户点击该段落时,需要突出显示该段落。这就是我实现它的方式,不要与高亮颜色混淆,它是我为此目的创建的自定义 NSAttributedString 键。
extension NSAttributedString.Key {
public static let highlightColor = NSAttributedString.Key.init("highlightColor")
}
class ReaderLayoutManager: NSLayoutManager {
// MARK: - Draw Background
override func drawBackground(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) {
super.drawBackground(forGlyphRange: glyphsToShow, at: origin)
self.enumerateLineFragments(forGlyphRange: glyphsToShow) { (_, usedRect, _, range, _) in
guard let highlightColor = self.currentHighlightColor(range: range) else { return }
guard let context = UIGraphicsGetCurrentContext() else { return }
var lineRect = usedRect
lineRect.origin.y += 10
lineRect.size.height -= 2
context.saveGState()
let path = UIBezierPath(roundedRect: lineRect, cornerRadius: 2)
highlightColor.setFill()
path.fill()
context.restoreGState()
}
}
private func currentHighlightColor(range: NSRange) -> UIColor? {
guard let textStorage = textStorage else { return nil }
guard let highlightColor = textStorage.attributes(at: range.location, effectiveRange: nil)[.highlightColor] as? UIColor else { return nil }
return highlightColor
}
}
当用户单击它时,我设置范围的突出显示颜色并重置 TextView。
attributedString.addAttributes([.highlightColor: theme.textUnderlineColor], range: range)