Search code examples
swiftstrikethrough

How to Cross strike cell button in swift 4


How to Cross strike cell button in swift 4

presently i am using the below code to strike button

func testString (titleStr : String) -> NSMutableAttributedString {
    let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: titleStr)
    attributeString.addAttribute(NSBaselineOffsetAttributeName, value: 1, range: NSMakeRange(0, attributeString.length ))
    attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 1, range: NSMakeRange(0, attributeString.length  ))
    attributeString.addAttribute(NSStrikethroughColorAttributeName, value: UIColor.red, range:  NSMakeRange(0, attributeString.length))
    return attributeString
}

And get output Like this 1: enter image description here

How to change my code to get output like this Screen shot 1: enter image description here


Solution

  • You can achieve that by using UIBezierPath. Create UIView above the button and set constraints to edges of button - right mouse button click on view and drag to the button:

    enter image description here

    hold shift and select all edges:

    enter image description here

    Then create custom UIView class with override draw(_ rect: CGRect) method:

    final class CrossedView: UIView {
    
        override func draw(_ rect: CGRect) {
            let path = UIBezierPath()
    
            path.move(to: .zero)
            path.addLine(to: CGPoint(x: frame.width, y: frame.height))
    
            path .move(to: CGPoint(x: 0, y: frame.height))
            path.addLine(to: CGPoint(x: frame.width, y: 0))
    
            UIColor.gray.setStroke()
            path.stroke()
        }
    
    }
    

    Next, set Class to CrossedView in storyboard, run.

    enter image description here

    Finally, you get expected result:

    enter image description here