问题
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