以编程方式更新约束

时间:2015-07-02 09:05:48

标签: ios objective-c ipad

情况就像我有一个带有四个按钮的视图

enter image description here

有一个条件是应该隐藏带有文本搜索社区的按钮,并且选项按钮的宽度应该增加

enter image description here

在我的项目中第一次使用约束,我没有得到如何实现这一点。从以下两个图像中可以清楚地看到在这两个按钮上添加的一组约束。

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

我在您的设置中看到的问题是在宽度相等的2个按钮之间存在此约束。这在第一种情况下是正确的,但是当你想要隐藏其中一种情况时,它就不再存在了。

因此,您需要重新考虑一下您的约束。也许不是等宽度约束,你可以在第一个按钮(左边一个,你想要隐藏)中使用静态宽度约束。然后是第二个,对第一个有一个水平空间约束,对superView有一个尾随空间。

然后在VC中为第一个按钮的宽度约束创建一个插座,当你想要隐藏它时,你会做这样的事情:

self.searchButtonWidthConstraint.constant = 0 
UIView.animateWithDuration(0.3, animations: {  () -> Void in
       self.view.layoutIfNeeded() // if you want to animate the constraint change
})

如果您有疑问,请告诉我。祝你好运,希望它成功!

<强>更新

对于横向用例,您可以收听方向更改通知,以更新按钮的宽度约束

-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    self.searchButtonWidthConstraint.constant = LANDSCAPE_WIDTH
    UIView.animateWithDuration(duration, animations: {  () -> Void in
           self.view.layoutIfNeeded() // if you want to animate the constraint change
    })
} 

答案 1 :(得分:0)

enter image description here

向第一个按钮添加约束

  1. 领先空间到NewView(灰色)
  2. NewView的底部空间
  3. 顶部空间到顶部按钮(在第1张和第2张图片中为蓝色)
  4. 宽度(从底部 - 右部)enter image description here
  5. 将约束添加到第二个按钮

    1. NEwView的尾随空间
    2. NewView的底部空间
    3. 顶部空间到顶部按钮(在第1张和第2张图片中为蓝色)
    4. 水平空间FirstButton(搜索社区)
    5. 宽度