如果在addSubView之后调用,UIButton不会移动

所以我试图在点击后移动一个UIButton

单击button后调用_addMoreFields方法。

_addMoreFieldBtn是一个全局的UIButton 。 当我点击它没有任何反应。

奇怪的部分是,如果我注释掉addSubView代码,然后button移动。

如果我保留该代码,button不会移动。

有任何想法吗?

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

注:我也尝试改变框架,但我得到同样的问题。 它从我放到现有位置的新位置开始animation。

问题是iOS 6 / Xcode 4.5中的新项目默认启用了“Autolayout”。 Autolayout是“弹簧和Struts”的替代品(但它只适用于iOS 6)。 此function为视图添加了约束条件,优先于您在代码中尝试的移动。

所以有三个可能的解决办法:

1)以编程方式在button上创build新的约束。 Autolayout非常强大和灵活…特别是如果你想支持iPhone 5和更早的模型的足迹。 您可以通过查看WWDCvideo来了解有关如何执行此操作的更多信息: iOS和OS X自动布局简介

2)不要使用Autolayout。 在Storyboard中select一个视图,然后在File Inspector中取消选中“Use Autolayout”。

3)为button上的每个约束创buildIBOutlets。 然后在移动button之前,删除这些限制:

 @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是该button的父视图,该视图可以是self.view也可以不是)。

实际上,我认为最近发生的事情是你的子视图首先进入屏幕,因此优先,然后一旦子视图被删除,button会移动,如果你改变代码:

 [_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]; 

这应该解决你所有的问题

🙂