为什么我以编程方式使用 Autolayout 约束居中不起作用?

Why does my centering using Autolayout constraints programmatically not work?

我试图以编程方式简单地将我的 GridViewAutolayout 约束居中。已建议的答案 here and here 建议使用

NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal,
            toItem: self.gridView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant:0)

我正在添加这样的约束:

func setupConstraints() {

    let centerX = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal,
        toItem: self.gridView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant:0)

    let centerY = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal,
        toItem: self.gridView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant:0)

    self.view.addConstraints([centerX, centerY])
}

但是,这似乎对我不起作用。当 运行 应用程序时,视图位于左上角,控制台显示关于同时满足约束的问题的疯狂输出。

我想你没有添加这段代码

self.gridView.translatesAutoresizingMaskIntoConstraints = false

这应该有效:

func setupConstraints() {

    self.viewToCenter.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint(item: self.viewToCenter, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal,
        toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant:0).active = true

    NSLayoutConstraint(item: self.viewToCenter, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal,
        toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant:0).active = true
}

您的第一项和第二项是错误的,不要使用 addConstraints,因为它已经或将被弃用 (iOS <= 8)。