Create UIButton in code (swift)

Adding and customizing UIButtons in storyboard is extremely easy (and I would recommend doing it that way whenever possible), but what if you need to do it yourself in code?

The process takes only couple of lines of code, but it can escalate quickly if you add multiple buttons. To keep code clean I’ve created a quick function to create them quickly:

    func createNewUIButton(title: String, textSizeDelta: CGFloat?, backgroundColor: UIColor?, cornerRadius: Bool, cornerColor: UIColor?) -> UIButton{

 

        let button = UIButton(type: .system)

        button.translatesAutoresizingMaskIntoConstraints = false

        button.setTitle(”  \(title)  “, for: .normal)

        button.titleLabel!.font = UIFont.systemFont(ofSize: UIFont.systemFontSize + (textSizeDelta ?? 0))

        if backgroundColor != nil{

            button.backgroundColor = backgroundColor!

        }

        if cornerRadius == true{

            button.layer.masksToBounds = true

            button.layer.cornerRadius = 7.5

            button.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMinYCorner]

            button.layer.borderWidth = 2

            button.layer.borderColor = cornerColor?.cgColor ?? UIColor.darkGray.cgColor

        }

       

        return button

 

    }

 

Once you get the button make sure you add constraints (if needed) and action and you’re good to go!

For reference, example of adding the action after you’ve instantiated the button:

button.addTarget(self, action: #selector(FUNCTION_GOES_HERE), for: .touchUpInside)

 

Questions / comments / suggestions? @MarcMasVi 

Marc