I’m trying to make ui using snapkit, but when I try to add stackview I keep getting error that says
‘Unable to activate constraint with anchors <NSLayoutYAxisAnchor:0x600001753fc0 “UIStackView:0x10380aba0.centerY”> and <NSLayoutYAxisAnchor:0x600001753a00 “UIImageView:0x103905b00.centerY”> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That’s illegal.’
When I comment out the stackview code line, everything works well, so I guess there is something wrong with the stackview.
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .darkGray
addSubview(userProfileImageView)
addSubview(stackView)
stackView.addArrangedSubview(userHandleLabel)
stackView.addArrangedSubview(locationLabel)
addSubview(rearViewImageView)
addSubview(captionLabel)
// constraint
userProfileImageView.snp.makeConstraints { make in
make.top.equalToSuperview().inset(5)
make.leading.equalToSuperview().inset(5)
//make.trailing.greaterThanOrEqualToSuperview().inset(100)
make.width.equalTo(userProfileImageView.snp.height).multipliedBy(1.0)
make.width.equalTo(50)
}
stackView.snp.makeConstraints { make in
make.centerY.equalTo(userProfileImageView.snp.centerY)
make.leading.equalTo(userProfileImageView.snp.trailing).offset(5)
}
rearViewImageView.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview()
make.height.equalTo(rearViewImageView.snp.width).multipliedBy(4.0 / 3.0)
make.centerX.equalToSuperview()
make.top.equalTo(userProfileImageView.snp.bottom).offset(10)
}
captionLabel.snp.makeConstraints { make in
make.leading.equalTo(rearViewImageView.snp.leading)
make.top.equalTo(rearViewImageView.snp.bottom).offset(5)
make.bottom.equalToSuperview().inset(10)
}
}
I tried making the stackview’s constraint with equalToSuperview(), but I get Fatal error: Expected superview but found nil when attempting make constraint
equalToSuperview.
error, so I guess stackview is not being added…?
I also double-checked that I’m adding subview before making constraints. I just can’t figure out what causes this error.