我在Storyboard中有一个视图控制器,它有一堆图像,标签和按钮,正确定位了视图在初始动画后的外观。
是否有一种简单的方法可以在init上保存每个元素的原始位置(也就是说它们在故事板上的位置),以便可以采用这些元素,将它们移出视图并将它们设置为Storyboard布局/位置?
答案 0 :(得分:1)
是的,这可以通过在数组中保存所有视图的约束,然后删除它们,并用新的屏幕外约束替换它们(我只有你想在self.view中移动所有内容时才能使用这个例子) - 如果您只想移动某些视图,则需要遍历所有self.view的约束,并仅添加与要移动到此数组的视图相关的约束。如果要将视图移动到其故事板定义的位置,请删除当前的视图,重新添加已保存的视图,并在动画块中调用layoutIfNeeded。
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *bottomButton;
@property (weak, nonatomic) IBOutlet UIButton *topButton;
@property (weak, nonatomic) IBOutlet UIButton *middleButton;
@property (strong,nonatomic) NSArray *finalConstraints;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *viewsDict = NSDictionaryOfVariableBindings(_bottomButton,_topButton,_middleButton);
self.finalConstraints = self.view.constraints; // save the storyboard constraints
[self.view removeConstraints:self.view.constraints]; // remove all the storyboard constraints
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_topButton]-(-30)-|" options:0 metrics:nil views:viewsDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_topButton]-(-30)-|" options:0 metrics:nil views:viewsDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_middleButton]-(-30)-|" options:0 metrics:nil views:viewsDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_middleButton]-(-30)-|" options:0 metrics:nil views:viewsDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_bottomButton]-(-30)-|" options:0 metrics:nil views:viewsDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_bottomButton]-(-30)-|" options:0 metrics:nil views:viewsDict]];
[self performSelector:@selector(moveToFinalPositions) withObject:nil afterDelay:2];
}
- (void)moveToFinalPositions {
[self.view removeConstraints:self.view.constraints];
[self.view addConstraints:self.finalConstraints];
[UIView animateWithDuration:2 animations:^{
[self.view layoutIfNeeded];
}];
}