有没有办法在Swift中以编程方式获取所有应用的自动布局约束

问题描述 投票:0回答:2

我想在没有任何参考的情况下使用storyboard获取所有应用约束的引用:

我尝试了很多方法,但无法找到确切的解决方案:

我的方法如下:

    if let constraint = (self.constraints.filter{$0.firstAttribute == .height}.first) {

}

使用上述方法,我只能找出高度。

if let topConstraint = (self.constraints.filter{$0.firstAttribute == .top}.first) {
            topConstraint.constant = 150//topMargin
        }
if let leadingConstraint = (self.constraints.filter{$0.firstAttribute == .leading}.first) {
            leadingConstraint.constant = 60 //leadingMargin
        }

对于topConstraint和leadingConstraint,我得到零。

self.constraints

self.constraints只提供一个只有高度的引用,即使我在同一视图上应用了前导,尾随和底部约束。

注意:我不想从故事板中获取参考,所以请不要建议解决方案。我想动态参考。

我正在寻找类似下面的方法:

 if let topConstraint = (self.constraints.filter{$0.firstAttribute == .top}.first) {
                topConstraint.constant = 150//topMargin
            }
   if let leadingConstraint = (self.constraints.filter{$0.firstAttribute == .leading}.first) {
                leadingConstraint.constant = 60 //leadingMargin
            }
   if let trailingConstraint = (self.constraints.filter{$0.firstAttribute == .trailing}.first) {
                trailingConstraint.constant = 70//leadingMargin
            }
   if let bottomConstraint = (self.constraints.filter{$0.firstAttribute == .bottom}.first) {
                bottomConstraint.constant = 150//49 + bottomMargin
            }

但不幸的是,上面一个不适合我:(

ios swift autolayout ios-autolayout
2个回答
0
投票

对于单个视图,您可以轻松获得与其相关的所有约束

for constraint in view.constraints {
   print(constraint.constant)
}

对于特定视图的所有子视图,您可以这样做

func getAllTheConstraintConstantsFor(view:UIView) {

   for constraint in view.constraints {
      print(constraint.constant)
   }

   for subview in view.subviews {
      self.getAllTheConstraintConstantsFor(view: subview)
   }
}

在这里你可以通过self.view,你将获得所有约束。


0
投票

参考this答案

对于像UIButton这样的视图,您可以使用此代码找到top约束。

extension UIButton {

    func findTopConstraint() -> NSLayoutConstraint? {
        for constraint in (self.superview?.constraints)! {
            if isTopConstraint(constraint: constraint) {
                return constraint
            }
        }
        return nil
    }

    func isTopConstraint(constraint: NSLayoutConstraint) -> Bool {
        return (firstItemMatchesTopConstraint(constraint: constraint) || secondItemMatchesTopConstraint(constraint: constraint))
    }

    func firstItemMatchesTopConstraint(constraint: NSLayoutConstraint) -> Bool {
        return (constraint.firstItem as? UIButton == self && constraint.firstAttribute == .top )
    }

    func secondItemMatchesTopConstraint(constraint: NSLayoutConstraint) -> Bool {
        return (constraint.secondItem as? UIButton  == self && constraint.secondAttribute == .top)
    }
}

要在qazxsw poi上获得qazxsw poi约束,请使用此代码

top

同样,您可以在任何视图上找到任何约束。

注意:您需要自己管理UIButton案例。

© www.soinside.com 2019 - 2024. All rights reserved.