【问题标题】:Center View in superview超级视图中的中心视图
【发布时间】:2014-12-02 09:45:04
【问题描述】:

我正在尝试使用其父视图中的按钮使我的子视图居中。所以我希望子视图的中心成为超级视图的中心。我正在尝试使用以下代码:

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

不幸的是,当我尝试运行该程序时,它会中断。 (线程 1:信号 SIGABRT)

【问题讨论】:

标签: ios swift autolayout constraints


【解决方案1】:

你的代码触发了一个断言:

当添加到视图时,约束的项必须是 该视图(或视图本身)。

这意味着您必须在添加约束之前将menuView 作为子视图添加到self.view。您还应该将约束添加到self.view,而不是menuView。最后但同样重要的是,通过调用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)
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多