Reputation: 65
Here I had used activity indicator programmatically and given constraints programmatically but got crashed at the NSLayoutConstraint
returning an error can anyone help me how to resolve this ?
here is my error in console
2017-11-04 16:46:41.657 Ecommerce[2744:71044] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors and because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'
func showActivityIndicator(uiView: UIView) {
container.frame = uiView.frame
container.center = uiView.center
container.backgroundColor = UIColorFromHex(rgbValue: 0xffffff, alpha: 0.3)
loadingView.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
loadingView.center = uiView.center
loadingView.backgroundColor = UIColorFromHex(rgbValue: 0x444444, alpha: 0.7)
loadingView.clipsToBounds = true
loadingView.layer.cornerRadius = 10
customActivityIndicator.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
customActivityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge
customActivityIndicator.center = CGPoint(x: loadingView.frame.size.width / 2, y: loadingView.frame.size.height / 2)
loadingView.addSubview(customActivityIndicator)
view.isUserInteractionEnabled = false
container.addSubview(loadingView)
container.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(
item: container,
attribute: .centerX,
relatedBy: .equal,
toItem: view,
attribute: .centerX,
multiplier: 1.0,
constant: 0.0
).isActive = true
NSLayoutConstraint(
item: container,
attribute: .centerY,
relatedBy: .equal,
toItem: view,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0
).isActive = true
NSLayoutConstraint(item: container, attribute: .width, relatedBy: .equal, toItem: contentView, attribute: .width, multiplier: 1, constant: view.frame.size.width / 2).isActive = true
NSLayoutConstraint(item: container, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1, constant: view.frame.size.height / 2).isActive = true
contentView.addSubview(container)
customActivityIndicator.startAnimating()
}
Upvotes: 1
Views: 194
Reputation: 154731
Add your subviews before you create the constraints.
Move this line:
contentView.addSubview(container)
to before the creation/activation of the constraints.
Upvotes: 1