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
  • 2,449
  • 2
  • 16
  • 37

2 Answers2

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
  • 14,770
  • 2
  • 37
  • 67
-1

You can achieve by following:

sampleButton.layer.cornerRadius = 15
sampleButton.clipsToBounds = true
Bhavik Modi
  • 1,461
  • 13
  • 27