Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move UIButton programmatically. Objective-C Xcode

I've seen some solutions, none of which have worked for my issue.

I have a UIButton created by simply drag/dropping into the UIViewController in Storyboard editor.

The UIButton has an outlet linked to the .h file for the UIViewController associated to that view. It is also Synthesized in the .m file.

@property (strong, nonatomic) IBOutlet UIButton *answerButton;

I want to change the location of the button during run time like this;

CGRect btFrame = answerButton.frame;
btFrame.origin.x = xOne;
btFrame.origin.y = yOne;
answerButton.frame = btFrame;

However whenever I try this, the button refuses to move.

All other editing functions (like setTitle etc) are functional, but for some reason the frame won't move how I want it to.

like image 586
SamBo Avatar asked Dec 10 '12 09:12

SamBo


3 Answers

Simply uncheck "Use Autolayout" in the file inspector..

like image 138
Muhammad Ibrahim Avatar answered Nov 05 '22 19:11

Muhammad Ibrahim


.h file

    #import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    IBOutlet UIButton *theButton;
}
@property(nonatomic, strong) IBOutlet UIButton *theButton;
-(IBAction)moveTheButton:(id)sender;

@end

.m file

-(IBAction)moveTheButton:(id)sender{
CGRect btFrame = theButton.frame;
btFrame.origin.x = 90;
btFrame.origin.y = 150;
theButton.frame = btFrame;

}

This code moves the button from one point to another.

like image 26
RKY Avatar answered Nov 05 '22 18:11

RKY


Replace your code by the below, which includes code to remove auto resizing mask.

CGRect btFrame = answerButton.frame;
btFrame.origin.x = xOne;
btFrame.origin.y = yOne;
answerButton.autoresizingMask = UIViewAutoresizingNone;
answerButton.frame = btFrame;
like image 4
Paramasivan Samuttiram Avatar answered Nov 05 '22 19:11

Paramasivan Samuttiram