Swift UIView约束恒定高度更改时间获取LayoutConstraints警告

时间:2019-06-28 09:19:10

标签: ios swift

我的场景是,我在storyboard内实现了UIView,高度恒定为90。在这个UIView中,我有两个UIView height 25和另一个UICollectionView 54。现在,我正在尝试以编程方式将基本UIView的高度从90降低到35,但是却收到LayoutConstraints警告。为正确的方法提供一些解决方案。

下面的代码我正在使用

BottomGalleryHeight.constant = 90 // Changing to 35
photoGalleryView.layoutIfNeeded()

我的警告错误

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x282679360 UIView:0x102f30880.height == 25   (active)>",
    "<NSLayoutConstraint:0x282679450 UIView:0x102f306a0.height == 35   (active)>",
    "<NSLayoutConstraint:0x2826794a0 V:|-(0)-[UIView:0x102f30880]   (active, names: '|':UIView:0x102f306a0 )>",
    "<NSLayoutConstraint:0x28267e210 V:[UIView:0x102f30880]-(10)-[UICollectionView:0x10385e000]   (active)>",
    "<NSLayoutConstraint:0x28267d450 V:[UICollectionView:0x10385e000]-(1)-|   (active, names: '|':UIView:0x102f306a0 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x282679360 UIView:0x102f30880.height == 25   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

2 个答案:

答案 0 :(得分:2)

这是如何使它工作的方法,

class VC: UIViewController {
    @IBOutlet weak var outerViewHeight: NSLayoutConstraint!
    @IBOutlet weak var innerViewHeight: NSLayoutConstraint!
    @IBOutlet weak var collectionViewHeight: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func onTapButton(_ sender: UIButton) {
        outerViewHeight.constant = 35.0
        innerViewHeight.constant = 10.0
        collectionViewHeight.constant = 25.0

        UIView.animate(withDuration: 0.3) {
            self.view.layoutIfNeeded()
        }
    }
}

enter image description here

答案 1 :(得分:0)

以下用于调整约束恒定高度的工作代码

// to update height constant
photoGalleryView.updateConstraint(attribute: NSLayoutAttribute.height, constant: 20.0)

extension UIView {    

    func updateConstraint(attribute: NSLayoutAttribute, constant: CGFloat) -> Void {
        if let constraint = (self.constraints.filter{$0.firstAttribute == attribute}.first) {
            constraint.constant = constant
            self.layoutIfNeeded()
        }
    }
}