Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

button

ios

swift

I have created a custom UIButton 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
 button_1.layer.borderWidth=2.0
like image 642
arda30 Avatar asked Jul 16 '16 16:07

arda30


1 Answers

You can create your own class that extends from UIButton

import UIKit

@IBDesignable
final class CoyoteButton: UIButton {

    var borderWidth: CGFloat = 2.0
    var borderColor = UIColor.white.cgColor

    @IBInspectable var titleText: String? {
        didSet {
            self.setTitle(titleText, for: .normal)
            self.setTitleColor(UIColor.black,for: .normal)
        }
    }

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

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        setup()
    }

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

To set a text to the button, just write myButton.titleText = "myText".

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.

like image 86
Brigadier Avatar answered Oct 05 '22 08:10

Brigadier