Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print out all constraints constant in Swift IOS?

Tags:

ios

swift

I can able to print out main view constraints constant by using,

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

but it will not iterate through subviews to print their constraints too. so for that, i have...

for subview in view.subviews {
    for v in subview.constraints {
        print(v.constant)
    }
}

now the question is what if the subview is a view itself?. in this case, how to print out the subview->view constraint constants. may be the view which is in subview may have its own subview and so on...

To fix this issue , i can simply create outlets for all views and then i have to iterate them one by one to get its constraint constants.

but i feel there must be easy way to print out all constraint constants ( all the constraints which are created in storyboard under particular view controller ) full programatically without creating outlets.

In short :

How to Print out all the storybaord constraint constants from view controller please note : the view controller may have several views and subviews and the subviews may have it own subviews. so we need to create an algorithm which will work efficiently in printing out constraint constant in any type of viewcontrollers if used.

like image 589
Satizh J Avatar asked Dec 02 '22 12:12

Satizh J


2 Answers

With a general-purpose recursive traversal method

extension UIView {
    func callRecursively(level: Int = 0, _ body: (_ subview: UIView, _ level: Int) -> Void) {
        body(self, level)
        subviews.forEach { $0.callRecursively(level: level + 1, body) }
    }
}

you can get your output with

    view.callRecursively { subview, level in
        for constraint in subview.constraints {
            print(String(repeating: " ", count: level),  constraint.constant)
        }
    }

The each output line is indented according to the nesting level in the view hierarchy.


Another example how that recursive method can be used: Find all subviews of a certain type:

    view.callRecursively { subview, _ in
        if let label = subview as? UILabel {
            print(label.text ?? "<none>")
        }
    }
like image 141
Martin R Avatar answered Dec 19 '22 18:12

Martin R


This is a perfect place to use recursion. Write a printConstraintConstants(for:) function and have it print out the constants for the current view and have it call itself for all subviews of the current view:

func printConstraintConstants(for view: UIView) {
    for constraint in view.constraints {
        print(constraint.constant)
    }

    for subview in view.subviews {
        printConstraintConstants(for: subview)
    }
}
like image 38
vacawama Avatar answered Dec 19 '22 17:12

vacawama