Search code examples
iosswiftuiviewuibuttonstoryboard

Swift how to move UIButton programmatically?


I have an infoButton UIButton outlet in my swift file. This button is originally placed in the storyboard with the following constraints:

Constraints picture

I want to move this button down by 50 pixels depending if NoAds boolean is true or false.

I have tried doing this, but I can't seem to move it.

if NoAds{
            print("No Ads")
            infoButton.center.y = infoButton.center.y - 50
        }else{
            print("Ads")
            loadBanner()
        }

I assume this should be an easy fix?

EDIT: The ad is a standard google ad banner which is 320 wide and 50 high.


Solution

    1. have an outlet for the top constraint enter image description here

    2. change the topConstraint.constant

    like this:

    if NoAds{
            print("No Ads")
            //topConstraint.constant -= 50
            topConstraint.constant = 50 // Avoid using -= or +=  if this func will call a lot of time
    }else{
            print("Ads")
    
            // set the default constant you want
            topConstraint.constant = 100
            loadBanner()
    }