Swift SnapKit如何根据相对位置布局UIView

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)
        }
    }

我想把 stackBoxOne 放在 textField 下面。但是上面的代码不起作用。我该如何修改代码?感谢您的宝贵时间。

您不能在 makeConstraints 闭包内使用 textField.frame,因为此时尚未对视图进行布局。因此,高度为 0stackBoxOne 的偏移量为 0

要将一个视图放置在另一个视图下方,您可以将其顶部约束连接到另一个视图的底部约束。所以在你的情况下:

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)
}

除此之外,您还可以将左右约束设置为等于 textFields 左右约束,如下所示:

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