2012-12-10 67 views
10

我見過一些解決方案,其中沒有一個適用於我的問題。如何以編程方式移動UIButton。 Objective C xCode

我有一個UIButton通過簡單拖放到故事板編輯器中的UIViewController創建。

UIButton有一個出口鏈接到與該視圖關聯的UIViewController的.h文件。它也在.m文件中合成。

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

我想在運行時更改按鈕的位置,就像這樣;

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

但是每當我嘗試這個,按鈕拒絕移動。

所有其他編輯功能(如setTitle等)功能正常,但出於某種原因,框架將無法移動到我想要的狀態。

任何見解/幫助將不勝感激。

+0

是否使用自動佈局使用手勢功能 –

+3

? – Zaphod

+0

@Vikas,用戶沒有移動按鈕。按鈕的位置取決於它們之前所做的一些選擇。 xOne,yOne是2個int值,創建一個根據之前所做選擇而改變的點。我只想將幀設置爲這些已知的int值。 – SamBo

回答

19

只需取消選中「使用自動佈局」中的文件檢查..

4

用下面的代碼替換您的代碼,其中包括刪除自動調整大小掩碼的代碼。

CGRect btFrame = answerButton.frame; 
btFrame.origin.x = xOne; 
btFrame.origin.y = yOne; 
answerButton.autoresizingMask = UIViewAutoresizingNone; 
answerButton.frame = btFrame; 
+3

欣賞您的回覆。試過了,沒有工作。 – SamBo

+0

你NSLog xOne,yOne並檢查它是什麼? –

7

h文件

#import <UIKit/UIKit.h> 

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

@end 

.m文件

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

}

該代碼從一個點移動按鈕到另一個。

相關問題