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

Animating UIView by changing constraints

That’s one of the most fun and easiest animations you can do.

First, let’s make sure we know what constraint to change: you’ll have to make sure you either have the constraint as an @IBOutlet or -if you’ve added in code- make sure you add an identifier to it. 

Then you’ll trigger a constant change within an animation block, in this first example we’re using the identifier to find the right constraint:

        UIView.animate(withDuration: 0.2) {

            let identifyTheRightConstraint = self.parent!.view.constraints.filter{ $0.identifier == “distanceOfMessageToTop” }

            if let constraint = identifyTheRightConstraint.first{

                constraint.constant = 0

            }

            self.parent!.view.layoutIfNeeded()

 

        }

 

Or this is you’re using an @IBOutlet

        UIView.animate(withDuration: 0.2) {

 

            IBOutletConstraint.constant = 0

 

            self.parent!.view.layoutIfNeeded()

 

        }

 

It’s very important that you’re triggering layoutIfNeeded() for the parent view of the view you’re changing the constraints on. And that’s it!  

Questions / comments / suggestions? @MarcMasVi 

Marc