gpt4 book ai didi

ios - 使用 NSLayoutConstraints 移动 UIView 所需的建议

转载 作者:行者123 更新时间:2023-11-29 04:08:58 25 4
gpt4 key购买 nike

从下面的图像中,当用户点击 view1 时,我让 view2 和 view3 向下滑动到页脚,通过将 view3 的约束常量与页脚设置为 0(ish)来有效地拉动。我的 xib 设置了约束,如第一张图所示。其中最重要的两个(现在对我来说)是 view1View2 约束和 view3Footer 约束

xib with constraints and views

为了实现向下滑动,我最终为 view1view2 约束设置了较低的优先级,为 view3Footer 约束设置了较高的优先级,然后在 animateWithDuration 中更新了 view3Footer 约束常量

successful slide down

我的问题是让 view2 和 view3 向后滑动,如果我使用相同的方法,我可以通过将 view1view2 约束常量设置为 2 来实现。

我认为上述向上滑动的问题是 view3Footer 约束比 view1View2 约束具有更高的优先级,优先级似乎只是只读的,所以我无法具体更改它们。我知道在设置约束时我只是请求 View 定位。

...我相信我可能完全使用了错误的方法...

我是否以正确的方式处理这件事?我是否必须获取约束对象 IBOutlet 并重写它们?如果是这样,我是否要重写优先级?我是否应该对具有相同优先级的常量使用 >= ,这似乎不起作用。我的简单向下动画的代码如下,虽然不多,但除了手势识别器之外,设置主要在 xib 中

非常感谢任何帮助。谢谢,史蒂夫

对于下滑:

[UIView animateWithDuration:0.9 animations:^{
_view3FooterConstraint.constant=2;
[self.view layoutIfNeeded];
} completion:^(BOOL finished){}];

UPDATE也尝试过这个设置优先级相等——无法再实现下滑

_view3FooterConstraint.constant=2;
[self.view setNeedsUpdateConstraints];
[UIView animateWithDuration:0.9 animations:^{
[self.view layoutIfNeeded];
} completion:^(BOOL finished){}];

对于上滑:

[UIView animateWithDuration:0.9 animations:^{
_view1View2Constraint.constant=2;
[self.view layoutIfNeeded];
} completion:^(BOOL finished){}];

最佳答案

我想我只需添加和删除 2 个发生变化的约束(2 的顶部约束为 1,3 的底部约束为页脚)即可做到这一点。确保所有 View 都有明确的高度,并使 IBOutlet 符合我上面提到的 2 个约束。您实际上一次只需要其中之一,但您需要将两者添加到 IB 中,以便您可以为它们创建导出。在 viewDidLoad 中,我立即删除了底部的一个。这应该适用于纵向和横向。我使用的代码是:

implementation ViewController {
IBOutlet NSLayoutConstraint *conBottom;
IBOutlet NSLayoutConstraint *conTop;
int pos;
}

-(void)viewDidLoad{
[super viewDidLoad];
pos = 0;
[self.view removeConstraint:conBottom];
[self.view layoutSubviews];
}


-(IBAction)togglePosition:(id)sender { //tap recognizer on view one action method
if (pos == 0) {
[self moveDown];
}else{
[self moveUp];
}
}

-(void)moveDown {
[self.view removeConstraint:conTop];
[self.view addConstraint:conBottom];
conBottom.constant=2;
[UIView animateWithDuration:0.9 animations:^{
[self.view layoutIfNeeded];
} completion:^(BOOL finished) {
pos = 1;
}];
}

-(void)moveUp {
[self.view removeConstraint:conBottom];
[self.view addConstraint:conTop];
conTop.constant=2;
[UIView animateWithDuration:0.9 animations:^{
[self.view layoutIfNeeded];
}completion:^(BOOL finished) {
pos = 0;
}];
}

关于ios - 使用 NSLayoutConstraints 移动 UIView 所需的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14707348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com