[英]UIButton does not move if called after addSubView
所以我試圖在點擊后移動UIButton
。
單擊按鈕后調用_addMoreFields
方法。
_addMoreFieldBtn
是一個全局UIButton
。 當我點擊它沒有任何反應。
奇怪的是,如果我注釋掉addSubView
代碼,那么按鈕會移動。
如果我保留該代碼,則按鈕不會移動。
有任何想法嗎?
-(void)movePlusButton {
NSLog(@"Moving button");
[UIButton beginAnimations:nil context:nil];
[UIButton setAnimationDuration:0.3];
_addMoreFieldsBtn.center = CGPointMake(30,30);
[UIButton commitAnimations];
}
- (IBAction)addMoreFields:(id)sender {
CGRect currentBtnFrame = [(UIButton *)sender frame];
CGPoint org = currentBtnFrame.origin;
UILabel *whoWasIn = [[UILabel alloc] initWithFrame:CGRectMake(110, org.y, 85, 21)];
whoWasIn.text = @"test";
UITextField *whoWasInField = [[UITextField alloc] initWithFrame:CGRectMake(59, whoWasIn.frame.origin.y+40, 202, 30)];
whoWasInField.placeholder = @"test2";
UILabel *with = [[UILabel alloc] initWithFrame:CGRectMake(136, whoWasInField.frame.origin.y+40, 49, 21)];
with.text = @"with";
whoWasInField.borderStyle = UITextBorderStyleRoundedRect;
UITextField *withField = [[UITextField alloc] initWithFrame:CGRectMake(59, with.frame.origin.y+40, 202, 30)];
withField.placeholder = @"test3";
withField.borderStyle = UITextBorderStyleRoundedRect;
[_homeView addSubview:whoWasIn];
[_homeView addSubview:with];
[_homeView addSubview:whoWasInField];
[_homeView addSubview:withField];
[self movePlusButton];
}
注意:我也嘗試更改框架,但我遇到了同樣的問題。 它從我放到現有位置的新位置開始動畫。
問題是iOS 6 / Xcode 4.5中的新項目默認啟用了“Autolayout”。 Autolayout是“Springs and Struts”的替代品(但它僅適用於iOS 6)。 此功能會向視圖添加約束,該約束優先於您在代碼中嘗試的移動。
所以有三種可能的解決方法:
1)以編程方式在按鈕上創建新約束。 Autolayout非常強大且靈活......特別是如果你想要支持iPhone 5和早期型號的足跡。 您可以通過查看WWDC視頻找到有關如何執行此操作的更多信息: iOS和OS X的自動布局簡介
2)不要使用Autolayout。 在Storyboard中選擇一個視圖,然后在文件檢查器中取消選中“使用Autolayout”。
3)為按鈕上的每個約束創建IBOutlets。 然后在移動按鈕之前,刪除這些約束:
@interface MyViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *addMoreFieldsBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *hConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *vConstraint;
- (IBAction)addMoreFields:(id)sender;
@end
和...
-(void)movePlusButton {
NSLog(@"Moving button");
[self.view removeConstraint:self.hConstraint];
[self.view removeConstraint:self.vConstraint];
[UIButton beginAnimations:nil context:nil];
[UIButton setAnimationDuration:0.3];
_addMoreFieldsBtn.center = CGPointMake(30,30);
[UIButton commitAnimations];
}
(您需要調用removeConstraints:
的實際視圖removeConstraints:
on是按鈕的父視圖,可能是也可能不是self.view)。
實際上,我認為發生的事情是你的子視圖首先進入屏幕,因此優先,然后一旦子視圖被刪除,按鈕就會移動,如果你改變代碼:
[_homeView addSubview:whoWasIn];
[_homeView addSubview:with];
[_homeView addSubview:whoWasInField];
[_homeView addSubview:withField];
[self movePlusButton];
} //移動[self movePlusButton]; 最多6行代碼,或使其成為第一行
[self movePlusButton];
[_homeView addSubview:whoWasIn];
[_homeView addSubview:with];
[_homeView addSubview:whoWasInField];
[_homeView addSubview:withField];
這應該可以解決你所有的問題
:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.