arda30 arda30 - 1 year ago 42
iOS Question

How to create a custom button and use multiple times in best way in iOS?

I have created a custom

in ios. I want to use the same custom button ten times with the same attributes but different titles. What is the most efficient and clever way to do this without repeating the same code for each button? Should it be a struct or a class or something else? How can I implement it? Attributes that I have changed for my custom button is as follows:

@IBOutlet weak var button_1: UIButton!

button_1.frame = CGRectMake(0.0, 0.0, button_1.frame.width, button_1.frame.height)
button_1.clipsToBounds = true
button_1.layer.cornerRadius = button_1.frame.width/2.0
button_1.layer.borderColor = UIColor.whiteColor().CGColor

Answer Source

You can create your own class that extends from UIButton

class MyOwnButton: UIButton {
     var borderWidth = 2.0
     var boderColor = UIColor.whiteColor().CGColor   

     override init(frame: CGRect){
         super.init(frame: frame)

     required init?(aDecoder: NSCoder) {
         super.init(aDecoder: aDecoder)

     override func layoutSubviews() {

     func setup() {
         self.clipsToBounds = true
         self.layer.cornerRadius = self.frame.size.width / 2.0
         self.layer.borderColor = borderColor
         self.layer.borderWidth = borderWidth

Then you can drag and drop a UIButton from the interface builder and then change the class of that button to your own MyOwnButton, or create one by code.