Chris Hutchison
Chris Hutchison

Reputation: 611

How to change a UIButton size and position through code not storyboard

Ive been messing around trying to change the size of a button in my storyboard scene through code, but every time I load the scene the button size is unchanged. I've tried changing the frame size of the button when the view loads, and I've also tried changing the frame through CGRect, and none of them seem to work. for example:

clickerbutton.frame = CGRect(x: 100, y: 100, width: 1000, height: 1000)

or

 clickerbutton.frame.size = CGSize(width: 100, height: 100)

Upvotes: 0

Views: 1374

Answers (2)

KSR
KSR

Reputation: 1709

To programatically layout button:

Add IBOutlets for each constraints of your button and change them in code.

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myButtonTopSpaceConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myButtonLeadingSpaceConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myButtonWidthConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myButtonHeightConstraint;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.myButtonLeadingSpaceConstraint.constant = 10;
    self.myButtonTopSpaceConstraint.constant =  20;
    self.myButtonWidthConstraint.constant = 200;
    self.myButtonHeightConstraint.constant = 70;

}

Use the following GitHub link to download sample project:

https://github.com/k-sathireddy/ButtonCustomLayout

If you want without constraints:

Create the button programmatically and then change frame as you want.

Upvotes: 0

Dravidian
Dravidian

Reputation: 9945

Make sure you are not using AutoLayout, as using autoLayout will not allow you to modify button size

Try using :-

 let dummyBtn : UIButton = UIButton() 

  override func viewDidLoad() {

    super.viewDidLoad()
    dummyBtn.frame = CGRect(x: 100, y: 100, width: 200, height: 150)
    dummyBtn.layer.backgroundColor = UIColor.blackColor().CGColor
    self.view.addSubview(dummyBtn)
    print(dummyBtn.frame)

}

func someFunction(){
  dummyBtn.frame = CGRectMake(x: 10, y: 10, width: 1000, height: 1000)
     }

Upvotes: 2

Related Questions