UIButton Changing Position

冷暖自知 提交于 2019-12-01 17:46:19
Retterdesdialogs

Remove Use Autolayout from the button in IB or storyboard.

If you want to adjust positions with Autolayout enabled, you will have to change your code like this

-(void)viewDidLayoutSubviews {

    screenSizeHeight=[UIScreen mainScreen].bounds.size.height;

    if(screenSizeHeight==568)
        mybuttonOutlet.frame= CGRect(38, 464 ,157,25);

    if(screenSizeHeight==480)
        mybuttonOutlet.frame= CGRect(38, 364 ,157,25);
}

Basically you need to perform any custom layout adjustments in viewDidLayoutSubviews method if Autolayout is enabled

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end


#import "ViewController.h"

@interface ViewController ()
@property(nonatomic, strong) IBOutlet UIButton *theButton;


// -(IBAction)moveTheButton:(id)sender;

@end

@implementation ViewController
@synthesize theButton;

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

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)moveTheButton:(id)sender{
    //set default position
    CGRect btFrame = theButton.frame;
    btFrame.origin.x = 145;
    btFrame.origin.y = 285;
    theButton.frame = btFrame;

    //position changing
    btFrame.origin.x += 40;
    theButton.frame = btFrame;

    //new size of button
    CGRect rect=CGRectMake(145, 285, 190, 30);
    [self.theButton setBounds:rect];

}

@end

I eventually went for the constraints. Get an outlet of the constraints that determine the position of the button (top, bottom, leading, trailing) and change the constraint(s) value(s).

self.constBtnSubmitTrailing.constraint = 50.0

This so you can keep AutoLayout enabled.

The solution I figured out for this is to create new View object inside the main View, and put my "dynamically changing objects" inside that View (as shown in picture).

Object hierarchy

Then I use Auto-Layout to position the new View in the main View. But bugButton:UIButton which is inside the new View, changes position as expected with:

bugButton.frame.origin = CGPoint(x: newX, y: newY)
Ruchira Randana

Please perform this check.

-(void)viewDidLoad{
    if(self.mybuttonOutlet==nil)NSLog(@"Button is NIL");
}

Now if you get the log "Button is NIL", then probably you forgot to link your IB button to your variable mybuttonOutlet.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!