I want add a UIView in its contentView center.
@IBOutlet weak var contentView: UIView!
override func viewDidLoad() {
let view = UIView(frame: CGRectMake(0,0,100,100))
view.backgroundColor = UIColor.blueColor()
contentView.backgroundColor = UIColor.redColor()
contentView.addSubview(view)
view.center = contentView.center
}
But the result is
Did I forget something?
Update thanks @Wain's tip, Constrain work. According to https://stackoverflow.com/a/27624927/6006588
override func viewDidLoad() {
let view = UIView(frame: CGRectMake(0,0,100,100))
view.backgroundColor = UIColor.blueColor()
contentView.backgroundColor = UIColor.redColor()
view.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(view)
let widthConstraint = NSLayoutConstraint(item: view, attribute: .Width, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100)
let heightConstraint = NSLayoutConstraint(item: view, attribute: .Height, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100)
let xConstraint = NSLayoutConstraint(item: view, attribute: .CenterX, relatedBy: .Equal, toItem: contentView, attribute: .CenterX, multiplier: 1, constant: 0)
let yConstraint = NSLayoutConstraint(item: view, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([heightConstraint, widthConstraint,xConstraint, yConstraint])
}
I think I use constraint in StoryBoard to contentView (centerX , centerY , Equal Width , Equal Height to superView).
The contentView will have incorrect frame size in ViewDidLoad.
And when I set view.center = contentView.center it don't work.
I need use constraint programmatically to set view's position.
Thanks.