更改 UIView 的框架并更新其子级的约束

ur3*_*r3k 1 constraints uiview ios swift

我需要根据按下的按钮来更改 UI 元素,基本上它就像一个选项卡,但只是我的视图控制器的一部分。我需要显示/隐藏的元素是 UIView,其中包含多个集合视图和标签。

我现在正在做的是以 IB 和编程方式定义两个对象,当我需要显示一个对象时,我只需将其中一个对象的宽度设置为 0,并为另一个对象设置一个具有我想要的整个宽度的新框架。这种方法的问题在于,即使 UIView 是我想要的样子,里面的内容似乎仍保留先前的约束(居中),并且它们不会“适应”整个宽度。

当前代码:

var newFrame = self.view.frame
newFrame.origin.x = 0
newFrame.origin.y = self.blueView.frame.origin.y
newFrame.size.height = self.blueView.frame.size.height

if (showGreen){

    self.greenView.frame = newFrame
    self.greenView.hidden = false
    self.blueView.frame.size.width = 0.0
    self.blueView.hidden = true

}else{

    self.blueView.frame = newFrame
    self.blueView.hidden = false
    self.greenView.frame.size.width = 0.0
    self.greenView.hidden = true
}
Run Code Online (Sandbox Code Playgroud)

在 IB 中,我为两个视图设置了约束,使其与边距之间没有分隔。

我希望您帮助我解决此问题或以其他方式实现所需的行为。

谢谢。

当前情况和期望的行为

Ale*_*kov 5

你应该改变constraint.constant值,而不是UIView的框架,为你需要的约束创建一个IBOutlets,然后改变它:

self.widthConstraint.constant = newValue;
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }];
Run Code Online (Sandbox Code Playgroud)