蔡祥霖 蔡祥霖 - 3 months ago 9
iOS Question

Why add UIView in contentView center always not in center?

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

enter image description here

Did I forget something?

Update
thanks @Wain's tip, Constrain work.
According to http://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.

Answer

You can use this code

@IBOutlet weak var contentView: UIView!

Then add this to viewDidLoad

let view = UIView(frame: CGRectMake(0,0,100,100))
let contentView = UIView(frame: self.view.frame)
view.backgroundColor = UIColor.blueColor()
contentView.backgroundColor = UIColor.redColor()
view.center = contentView.center
contentView.addSubview(view)
self.view.addSubview(contentView)

This is the result

enter image description here

Comments