0

Very new to Swift and iOS development. What is the correct way to customise a UIButton?

I am looking to make a UI button that is just a circle, but I want to have the same behaviour as the system buttons: it fades when highlighted, and the fading is animated.

Ideally I would do this without images, and use UIBezierPath, so I can keep a consistent border width for different sizes.

Jacob
  • 1,204
  • 1
  • 12
  • 25

1 Answers1

1

To make a circular button, you can just use the corner radius property! So long as the frame/bounds of the button are a square, if you set the cornerRadius to half of the width, it'll appear as a circle. First, you'll need to import the QuartzCore framework:

import QuartzCore

Corner Radius

To set the corner radius:

myButton.layer.cornerRadius = 8.0

To make a circle given an arbitrary frame, you can use the following:

myButton.layer.cornerRadius = myButton.frame.size.width / 2.0

You may have to set the clipsToBounds property for the corner radius change to be visible:

myButton.clipsToBounds = true

Border

You can also use the layer property to set your border:

myButton.layer.borderWidth = 1.0
myButton.layer.borderColor = UIColor.purpleColor()

(See this post for more examples in Objective-C)

Community
  • 1
  • 1
Carter
  • 2,803
  • 1
  • 13
  • 21
  • Is there a way to get the border to reflect the tint color when highlighted, and also animate using the system animation? – Jacob May 18 '16 at 21:06
  • I'm not sure if you can keep the system animation- I assume it will stay but I'm not sure :) To have the border change color and animate on touches, you can add a target for `.TouchDown` and `.TouchUpInside | .TouchUpOutside`. For example: `myButton.addTarget(self, action: "changeHighlightAndAnimate", forControlEvents: .TouchDown)`. Then, in your `changeHighlightAndAnimate` function, change the border color and animate the fade. – Carter May 18 '16 at 21:21