Resizing a button in iOS programmatically
Asked Answered
V

1

7

I am using XCode 4.6.1 and developing for iOS 6.

I have added a button to the storyboard. I have created an outlet in my implementation file ViewController.m:

    //
    //  ViewController.m
    //

    #import "ViewController.h"

    @interface ViewController ()

    @property (weak, nonatomic) IBOutlet UIButton *b1;

    @end

I try to change the button b1's properties as follows (in this same file: ViewController.m):

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

        self.b1.alpha = 0.5;
        self.b1.frame = CGRectMake(0,0,123,412);
    }

When I run the app in the simulator, the alpha of the button is successfully set to 0.5. However, the position and size of the button doesn't change.

I have tried various ways to make it happen. However nothing seems to work. I would like to know what am I doing wrong. I am pretty new to Objective C. Any help would be greatly appreciated.

Vezza answered 14/6, 2013 at 9:22 Comment(1)
try setting the frame in viewDidLayoutSubviews instead of viewDidLoad.Paunchy
R
18

You are probably using autolayout:

enter image description here

When using autolayout you cannot manually change your outlets frames. You have two options: you can either disable autolayout (then your code should work), or create outlets to your constraints and then modify the constrains programmatically:

 @property (weak, nonatomic) IBOutlet NSLayoutConstraint *widthConstraint;

and then in your code:

 self.widthConstraint.constant = 123;

and so on with all the constraints that need to be modified.

Romulus answered 14/6, 2013 at 9:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.