2013-05-06 156 views
7

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

enter image description here

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

@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); 

} 
+0

你今天myButtonOutlet与你的.xib连接:预期与UIButton的是新的视图中,改变位置? – 2013-05-06 19:26:34

+0

我没有找到任何理由,除非您忘记连接IBOutlet,否则无法正常工作。 – Anupdas 2013-05-06 19:26:43

+0

是的,我把我的按钮连接到我的.xib – casillas 2013-05-06 19:27:15

回答

14

从IB或情节串连图板按钮删除Use Autolayout

+0

我相信你只能从整个xib/SB本身删除自动布局 - 这对我也有效。 – kraftydevil 2014-09-21 21:04:07

2

如果要调整启用了自动布局位置,你将不得不改变这样

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

你的代码基本上你需要执行viewDidLayoutSubviews方法的任何自定义布局调整如果启用了自动布局

0

请执行此检查。

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

现在,如果你得到的日志“按钮NIL”,那么很可能你忘了你的IB按钮链接到您的变量mybuttonOutlet。

0
#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 
0

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

self.constBtnSubmitTrailing.constraint = 50.0 

这样你可以保持AutoLayout启用。

0

我想出的解决方案是在主视图中创建新的View对象,并将该“视图内动态更改的对象”放入该视图中(如图所示)。

Object hierarchy

然后我用自动布局定位在主视图中的新景观。 但bugButton:

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