UIButton改变位置

我在IB有一个button。 我有一个IBOutlet设置和屏幕上的对象链接到它。 有没有办法以编程方式更改button位置和/或大小? 我知道你可以改变标题和一些东西,但我不知道如何改变它的位置或大小。

在这里输入图像说明

现在我想相应地改变它的立场。 可能吗? 如果是,请让我知道如何,因为我试图改变我的button在以下代码的位置,但它不起作用的头文件。

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

在执行文件中:

 -(void)viewDidLoad { 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); } 

从IB或故事板的button中移除Use Autolayout

如果你想在启用Autolayout的情况下调整头寸,你将不得不像这样改变你的代码

 -(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); } 

如果启用Autolayout,基本上你需要在viewDidLayoutSubviews方法中执行任何自定义的布局调整

 #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 

我最终去了约束。 获取确定button位置(顶部,底部,顶部,尾部)以及更改约束(s)值的约束条件。

 self.constBtnSubmitTrailing.constraint = 50.0 

这样你可以保持启用AutoLayout。

我想出的解决scheme是在主View中创build一个新的View对象,并在View中放置“dynamic变化的对象”(如图所示)。

对象层次结构

然后,我使用Auto-Layout将新视图定位在主视图中。 但是bugButton:位于新视图中的UIButton按预期方式更改位置:

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

请执行此检查。

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

现在,如果你得到日志“Button is NIL”,那么你可能忘了把你的IBbutton连接到你的variablesmybuttonOutlet。