Constrains count is always getting zero ( 0 ) in AutoLayout - iOS

社会主义新天地 提交于 2019-12-24 10:38:23

问题


I am getting one weird issue, I am setting constraints on the view using storyboard as below:

But if I am accessing all applied constraint by code then always getting zero (0).

for self.view it's returning the constraint but for yellow view getting zero.


回答1:


Use this code (Swift 4+ and Xcode 9.4.1)

import UIKit

class ViewController: UIViewController {

@IBOutlet var subView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    print(self.view.getAllConstraints().count)
    print(self.subView.getAllConstraints().count)
  }
}

extension UIView {

func getAllConstraints() -> [NSLayoutConstraint] {
    var views = [self]
    var view = self
    while let superview = view.superview {
        views.append(superview)
        view = superview
    }
    return views.flatMap({ $0.constraints }).filter { constraint in
        return constraint.firstItem as? UIView == self ||
            constraint.secondItem as? UIView == self
    }
   }
  }



回答2:


Just try to print constraints in viewDidAppear. In viewDidLoad method constraints not loaded for view so, just try in viewDidAppear method.




回答3:


for your information when viewDidLoad is called subviews is not laid out yet thats why you getting count zero put you code into viewDidLayoutSubviews you will get your constraints there



来源:https://stackoverflow.com/questions/52272096/constrains-count-is-always-getting-zero-0-in-autolayout-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!