2013-05-06 201 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)