问题是 iOS 6 / Xcode 4.5 中的新项目默认启用“自动布局”。 Autolayout 是“Springs and Struts”的替代品(但它仅适用于 iOS 6)。此功能向视图添加了约束,该约束优先于您在代码中尝试的移动。
因此,可以通过三种方式解决此问题:
1) 以编程方式在按钮上创建新约束。自动布局非常强大且灵活......特别是当您尝试支持 iPhone 5 和早期型号的占用空间时。您可以通过观看 WWDC 视频找到有关如何执行此操作的更多信息:iOS 和 OS X 自动布局简介 https://developer.apple.com/videos/wwdc/2012/?id=202
2)不要使用自动布局。在故事板中选择一个视图,然后在文件检查器中取消选中“使用自动布局”。
3) 为按钮上的每个约束创建 IBOutlet。然后在移动按钮之前,删除这些约束:
@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
and...
-(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:
on 是按钮的父视图,可能是也可能不是 self.view)。