简体   繁体   中英

Center View in superview

I'm trying to center my subview with a button in its superview. So I want the center of the subview be the center of the superview. I'm trying that with following code:

override func viewDidLoad() {
    self.view.backgroundColor = UIColor.redColor()

    var menuView = UIView()
    var newPlayButton = UIButton()
    //var newPlayImage = UIImage(named: "new_game_button_5cs")
    var newPlayImageView = UIImageView(image: UIImage(named: "new_game_button_5cs"))
    newPlayButton.frame = CGRectMake(0, 0, newPlayImageView.frame.width, newPlayImageView.frame.height)
    newPlayButton.setImage(newPlayImage, forState: .Normal)
    newPlayButton.backgroundColor = UIColor.whiteColor()

    menuView.backgroundColor = UIColor.whiteColor()
    menuView.addSubview(newPlayButton)

    menuView.addConstraint(
        NSLayoutConstraint(item: self.view,
            attribute: .CenterX,
            relatedBy: .Equal,
            toItem: menuView,
            attribute: .CenterX,
            multiplier: 1, constant: 0)
    )
}

Unfortunately the program breaks when I try to run it. (Thread 1: signal SIGABRT)

Your code triggers an assertion saying:

When added to a view, the constraint's items must be descendants of that view (or the view itself).

This means you have to add menuView as a subview to self.view before adding constraints. You should also add the constraints to self.view , not the menuView . Last but not least, remove autoresizing masks constraints that were implicitly added to menuView by calling setTranslatesAutoresizingMaskIntoConstraints(false) or autolayout will complain about conflicting constraints.

menuView.addSubview(newPlayButton)
menuView.setTranslatesAutoresizingMaskIntoConstraints(false)

self.view.addSubview(menuView)
self.view.addConstraint(
    NSLayoutConstraint(item: self.view,
        attribute: .CenterX,
        relatedBy: .Equal,
        toItem: menuView,
        attribute: .CenterX,
        multiplier: 1, constant: 0)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM