Search code examples
swiftsnapkit

Swift SnapKit how to layout UIView with relative position


func setupPosition() {
        box.snp.makeConstraints{(make)->Void in
        make.edges.equalTo(view).inset(UIEdgeInsetsMake(64+20, 20, 250, 20))
        }

        textField.snp.makeConstraints{(make)->Void in
            make.edges.equalTo(box).inset(UIEdgeInsetsMake(5, 5, 150, 5))

        }

        stackBoxOne.snp.makeConstraints{(make)->Void in
                make.top.equalTo(box).offset(textField.frame.size.height)
                make.left.equalTo(box).offset(5)
                make.bottom.equalTo(box).offset(-90)
                make.right.equalTo(box).offset(-5)
        }
    }

I want to put the stackBoxOne under the textField. But the above code isn't working. How can I modify the code? Appreciate for your time.


Solution

  • You cannot use textField.frame inside the makeConstraints closure because the views have not been layouted at that point. Because of that the height is 0 and stackBoxOne gets an offset of 0.

    To place a view underneath another view you connect its top constraint to the bottom constraint of the other view. So in your case:

    stackBoxOne.snp.makeConstraints{(make)->Void in
         make.top.equalTo(textField.snp.bottom)
         make.left.equalTo(box).offset(5)
         make.bottom.equalTo(box).offset(-90)
         make.right.equalTo(box).offset(-5)
    }
    

    In addition to that you can also set the left and right constraint equal to the textFields left and right constraint like this:

    stackBoxOne.snp.makeConstraints{(make)->Void in
        make.top.equalTo(textField.snp.bottom)
        make.left.right.equalTo(textField)
        make.bottom.equalTo(box).offset(-90)
    }