简体   繁体   English

超级视图中的中心视图

[英]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) (线程1:信号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. 这意味着你必须添加menuView作为一个子视图,以self.view添加约束之前。 You should also add the constraints to self.view , not the menuView . 你也应该限制添加到self.view ,而不是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. 最后但并非最不重要的一点是,通过调用setTranslatesAutoresizingMaskIntoConstraints(false)来删除隐式添加到menuView的自动调整大小蒙版约束,否则自动布局会抱怨冲突的约束。

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)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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