1

I'm fairly new to Swift and I'm trying to understand how to edit UIButtons to make them look a certain way. I would like to know how I can make my UIButtons look like:

this

rmaddy
  • 314,917
  • 42
  • 532
  • 579

2 Answers2

4

try this:

extension UIView {
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat, borderColor: UIColor?, borderWidth: CGFloat?) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))

        let mask = CAShapeLayer()
        mask.frame = self.bounds
        mask.path = path.cgPath
        self.layer.mask = mask

        if borderWidth != nil {
            addBorder(mask, borderWidth: borderWidth!, borderColor: borderColor!)
        }
    }

    private func addBorder(_ mask: CAShapeLayer, borderWidth: CGFloat, borderColor: UIColor) {
        let borderLayer = CAShapeLayer()
        borderLayer.path = mask.path
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.strokeColor = borderColor.cgColor
        borderLayer.lineWidth = borderWidth
        borderLayer.frame = bounds
        layer.addSublayer(borderLayer)
    }
}

usage:

someView.roundCorners([.topLeft, .topRight], radius: 3, borderColor: nil, borderWidth: nil) //top corners with radius 3 without border
someView.roundCorners(.allCorners, radius: 2, borderColor: UIColor.red, borderWidth: 1) //all corners with red border

you can apply this to any UI element, that inherits UIView (for example UIButton)

JuicyFruit
  • 2,638
  • 2
  • 18
  • 35
0

In this case I would make a transparent button with the white text.

Then I would define the color and size of the border:

self.myButton.layer.layer.borderColor  = UIColor.white
self.myButton.layer.layer.borderWidth  = 3

Next I would round the button:

self.myButton.layer.cornerRadius = 3
self.myButton.clipsToBounds = true

To make the background red just put the button on top of a view of this color

breno
  • 230
  • 2
  • 15