为什么我不能创建NSLayoutConstraint类型的数组?

时间:2016-03-07 02:39:36

标签: ios arrays swift xcode7

基本上,我试图在用户点击按钮时重置一些NSConstraints。

我的约束出口:

@IBOutlet weak var firstButtonHeight: NSLayoutConstraint!
@IBOutlet weak var secondButtonheight: NSLayoutConstraint!
@IBOutlet weak var thirdButtonHeight: NSLayoutConstraint!

示例操作:

@IBAction func firstButtonHeight(sender: UIButton) {
    firstButtonHeight.constant = 100
}



我想我可以将它们放入一个数组(下面)并在运行firstButtonHeight.constant = 100之前迭代它们

var constraints: [NSLayoutConstraint] = [firstButtonHeight, secondButtonheight, thirdButtonHeight]
for constraint in constraints {
    constraint.constant = 50 //Original constraint value
}

但是,我收到错误Instance member 'firstButtonHeight' cannot be used on type 'ViewController'。什么时候firstButtonHeight成为ViewController?

1 个答案:

答案 0 :(得分:1)

一个主要问题是,在constraints初始值设定项中,您提到了其他实例变量的名称。你不能那样做,因为在实例变量初始化时,实例还没有存在 - 这就是我们正在初始化的东西!

您可以通过将代码移动到初始化时间后运行的函数来轻松解决此问题:

class ViewController: UIViewController {

    @IBOutlet weak var firstButtonHeight: NSLayoutConstraint!
    @IBOutlet weak var secondButtonheight: NSLayoutConstraint!
    @IBOutlet weak var thirdButtonHeight: NSLayoutConstraint!

    func someFunction() {
        var constraints: [NSLayoutConstraint] = [firstButtonHeight, secondButtonheight, thirdButtonHeight]
        for constraint in constraints {
            constraint.constant = 50 //Original constraint value
        }
    }
}

仔细查看它与您正在做的事情之间的区别。

需要在另一个实例变量的初始化程序中提及实例变量的问题的常见解决方案是声明第二个实例变量lazy。请注意,当您执行此操作时,必须使用self(一般情况下,我建议您始终使用它)。因此,这将在视图控制器的顶层编译:

@IBOutlet weak var firstButtonHeight: NSLayoutConstraint!
@IBOutlet weak var secondButtonheight: NSLayoutConstraint!
@IBOutlet weak var thirdButtonHeight: NSLayoutConstraint!
lazy var constraints : [NSLayoutConstraint] = [self.firstButtonHeight, self.secondButtonheight, self.thirdButtonHeight]

但其余的for循环仍然需要存在于函数体内。