Is there an option to apply single strikethrough line for NSMutableAttributedString with different fonts?

58 Views Asked by At

I have an NSAttributedString with two different font sizes for displaying currency in pennys.

enter image description here

I need to apply strikethrough to all strings, but not to break line of strikethrough.

How can I draw a single strikethrough line in one formatting style? The result I need is this:

enter image description here

The current result when I apply attribute:

value.addAttributes([NSAttributedString.Key.strikethroughStyle : 2], range: value.range)

enter image description here

1

There are 1 best solutions below

0
son On BEST ANSWER

I think the simplest way is to draw a path above the label's layer. Try this:

extension UIView {
    func addCenterStrikeThrough(color: UIColor, width: CGFloat = 0.5) {
        let path = UIBezierPath()
        path.move(to: CGPoint(x: 0, y: frame.size.height / 2))
        path.addLine(to: CGPoint(x: frame.size.width, y: frame.size.height / 2))
        
        let layer = CAShapeLayer()
        layer.strokeColor = color.cgColor
        layer.lineWidth = width
        layer.path = path.cgPath
        
        self.layer.addSublayer(layer)
    }
}

Output

enter image description here