首页 > 解决方案 > iOS Hide button with equal width constraint

问题描述

So I am trying to implement some feature restrictions based on permissions in an app. The feature in question works on a button that is placed at the bottom of the VC in main.storyboard.

There is another button that I want to remain there. They are aligned horizontally, but not in a horizontal stack view. They have an equal-width constraint and together take up the whole vertical space at the bottom.

I want to hide the first one, and thus have the second one take up that entire horizontal space from left to right, but only when the access to the first button is supposed to be restricted. I've tried doing this in viewNeedsRefresh:

let equalWidthConstraint = firstButton.superview?.constraints.filter{
                $0.firstItem as? UIButton == firstButton && $0.secondItem as? UIButton == secondButton
            }.first
equalWidthConstraint?.isActive = false
firstButton.isHidden = true
secondButton.frame = CGRect(x: 0, y: firstButton.frame.origin.y, width: self.view.frame.width, height: firstButton.frame.height)

But all this does is hide the first button, while the second button is suddenly partially off-screen. If I try without manually disabling the constraint, I get it looking cleaner but the second button is still in its original position, likely because it still maintains the original width due to the constraint.

标签: iosswiftuibuttonnslayoutconstraint

解决方案


就个人而言,在我看来,我会做以下事情:

  1. 删除等宽约束
  2. 在其中一个按钮上设置宽度约束,设置为超级视图宽度的 0.5 倍,然后为该约束创建一个出口
  3. 将带有尾随或前导(取决于您选择的按钮)的另一个按钮设置为零。
  4. 当您需要折叠按钮时,您现在可以直接设置约束的常量,如下所示:

    buttonWidth.constant = 0
    

这将隐藏视图并为您提供所需的效果。


推荐阅读