Search code examples
iosswiftsnapkit

SnapKit- Unable to add constraints by looping through UIViews


I have multiple TextFields that I would like to apply similar layout constraints to. Instead of repeating such constraints, I created an array of tuples, of type (UITextField, UIView), where the UITextField is the textfield that I want to add constraints to, and the view is the view containing such textfield.

My code is as follows:

    let textFields: [(UITextField, UIView)] = ...

    for textFieldTuple in textFields {
        let textField = textFieldTuple.0!
        let view = textFieldTuple.1!

        textField.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(view.snp.top)
            make.bottom.equalTo(view.snp.bottom)
            make.left.equalTo(view.snp.left)
            make.right.equalTo(view.snp.right)
        }
    }

However, when I run my application, the app crashes, due to the first constraint in the closure. Am I able to make constraints from such a position, or should I explicitly write them for each TextField? Thanks

Crash details:

libc++abi.dylib: terminating with uncaught exception of type NSException


Solution

  • Before you set constraints between 2 items there should be a layout-dependency between them so add each textfield to the corresponding view before setting the constraints