0

I would like to cut the corners off of a UIButton in swift.

I know how to set a corner radius but I'd like to cut the corners.

// what I DON'T want, rounded corners
myButton.layer.cornerRadius = myButton.frame.height / 2

Cut off corners are for me:

enter image description here

swift-lynx
  • 3,219
  • 3
  • 26
  • 45

1 Answers1

0

Create a CAShapeLayer with the desired path like this

enter image description here

let button = UIButton()
button.backgroundColor = .red
button.frame = CGRect(x: 100, y: 100, width: 200, height: 40)
view.addSubview(button)

let layer = CAShapeLayer()
layer.fillColor = UIColor.yellow.cgColor

let cutSize:CGFloat = 20
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: button.bounds.midY))
path.addLine(to: CGPoint(x: cutSize, y: 0))
path.addLine(to: CGPoint(x: button.bounds.maxX-cutSize, y: 0))
path.addLine(to: CGPoint(x: button.bounds.maxX, y: button.bounds.midY))
path.addLine(to: CGPoint(x: button.bounds.maxX-cutSize, y: button.bounds.maxY))
path.addLine(to: CGPoint(x: cutSize, y: button.bounds.maxY))
path.addLine(to: CGPoint(x: 0, y: button.bounds.midY))

layer.path = path.cgPath
button.layer.insertSublayer(layer, at: 0)
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70