ios - super View 中的中心 View

标签 ios swift autolayout constraints

我正试图通过其父 View 中的按钮使我的 subview 居中。所以我希望 subview 的中心成为父 View 的中心。我正在尝试使用以下代码:

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)

最佳答案

您的代码触发断言说:

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

这意味着您必须在添加约束之前将 menuView 作为 self.view 的 subview 添加。您还应该将约束添加到 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)
)

关于ios - super View 中的中心 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27246234/

相关文章:

ios - 设置为自动换行时如何获取 UILabel 文本的实际宽度

ios - uinavigationcontroller 在 iOS 中恢复状态时失去色彩

ios - 如何清除使用 Firestore 作为其数据库的快速聊天应用程序的缓存?

swift - 我如何在 Swift 中遵守带有关联类型的协议(protocol)?

ios Auto-Layout UIView on 3.5 changing height on 4.0 inch

ios - tableView 中多个 NSTimer 对象的问题

iOS Base 本地化未用于缺少 key

ios - 如何一个一个地发出多个网络请求,这样我就不会丢失数据?

macos - NSScrollView 与宽度匹配的 DocumentView

ios - 使用自动布局时 UIScrollview 的中心内容