UIView 没有名为 'setTranslatesAutoresizingMaskIntoConstraints' 的成员

UIView does not have a member named 'setTranslatesAutoresizingMaskIntoConstraints'

我正在使用 Xcode 7 beta & Swift 2

我正在尝试通过 addController 操作将 ViewController (childVC) 添加到容器中。我想针对容器设置 ViewController 的自动布局。在下面的代码中,它给出了以下错误

UIView 没有名为 'setTranslatesAutoresizingMaskIntoConstraints' 的成员。 我也试过将 'false' 放在方括号中(见下面的注释行)——但即使那样也不起作用

我基本上是想让childVC占据整个容器。 childVC 有一个 tableview,它应该根据容器大小调整大小。

func addController(controller: UIViewController)
{
    addChildViewController(controller)
    containerView.addSubview(controller.view)


   controller.view.setTranslatesAutoresizingMaskIntoConstraints = false

   // controller.view.setTranslatesAutoresizingMaskIntoConstraints(false)
    var constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view" : controller.view])
    constraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view" : controller.view])
    NSLayoutConstraint.activateConstraints(constraints)
    didMoveToParentViewController(controller)
    currentController = controller

}

在 iOS9 之前,setTranslatesAutoresizingMaskIntoConstraints 是一个函数:

func setTranslatesAutoresizingMaskIntoConstraints(_ flag: Bool)

在 iOS 9 中变成了 属性:

 var translatesAutoresizingMaskIntoConstraints: Bool 

您必须决定是否只针对 iOS9,相应地设置部署目标,然后使用 属性。如果您支持 iOS 的旧版本,则可以使用 Swift 2.

的新可用性功能
if #available(iOS 9, *) {
    controller.view.translatesAutoresizingMaskIntoConstraints = false
} else {
    controller.view.setTranslatesAutoresizingMaskIntoConstraints(false)
}

我认为接受的答案不正确。至少它不会在 Xcode 7 上编译。如答案下方的评论之一所述。

使用 属性 语法就足够了,适用于 iOS 8 和 iOS 9:

controller.view.translatesAutoresizingMaskIntoConstraints = false

我认为这是因为 UIView 仍然是 Objective-C class 并且在这样的代码上设置 属性 无论如何都会在旧版本的 iOS 上调用 setTranslatesAutoresizingMaskIntoConstraints。

此外,Apple 文档将其定义为 属性:

var translatesAutoresizingMaskIntoConstraints: Bool

此语法从 iOS 6 开始可用,所以我认为这里甚至不推荐使用 #available。

参考请看: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instp/UIView/translatesAutoresizingMaskIntoConstraints

在Swift2中,setTranslatesAutoresizingMaskIntoConstraints方法变成了属性-translatesAutoresizingMaskIntoConstraints.

这与 API 版本无关,可用性检查(在 Swift 2 中也是新的)完全没有必要。

如果使用 Swift 2,只需在您的代码库中设置 属性 值。 如果从 Swift 1 升级,您可能会看到需要更新以前的函数调用的错误。

简单。