Milap Jhumkhawala Milap Jhumkhawala - 4 months ago 20
iOS Question

'Cannot Install Constraint', reason: 'No common superview between views

import UIKit
import SnapKit

class RecordButton: UIView {
let box = UIView()
let container = UIView()

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}

override init(frame: CGRect) {
super.init(frame: frame)
setup()
}

func setup() {
container.snp_makeConstraints { (make) -> Void in
make.width.equalTo(200)
make.height.equalTo(200)
make.center.equalTo(self.container)
}
box.snp_makeConstraints { (make) -> Void in
make.top.equalTo(container).offset(50)
make.left.equalTo(container).offset(50)
make.bottom.equalTo(container).offset(-50)
make.right.equalTo(container).offset(-50)
make.center.equalTo(container)
}
self.addSubview(container)
container.addSubview(box)
setColor()

}
func setColor() {
self.container.backgroundColor = UIColor.blackColor()
self.box.backgroundColor = UIColor.orangeColor()
}

}


Why is it showing this error? Is there any other way to execute this? Any Suggestion?. The centre.equalTo creates this error. I am new to swift and trying to implement SnapKit framework

Answer

That means your views or any controller should be in common view. For example, There is view A having two buttons say X and Y and view B have two buttons P and K then you can set constraint of P and K respected to it's super view B not with respect to view A.

If there are multiple super views then make sure that you have given proper constraint to every super view. then only endpoint view's constraints will be satisfied.

Uodate:

First add box in container and container in it's superview then set the constraints. and make sure that you are getting center in self.container and container for container view and box view respectively. If you are setting top,bottom,leading and trailing then not need to set center also!

Hope this will help :)