Swift 2:实例成员不能用于类型" View Controller"

时间:2016-03-05 21:08:10

标签: ios swift class uilabel

我是swift的新手,我正在尝试使用类和方法!我一直在寻找谷歌和stackoverflow找到答案!我已经阅读了多个同样问题的帖子,但他们仍然无法帮助我!我为一个更大的应用程序编写了快速代码,但决定写一小部分,所以我得到了同样的想法。我试图在按下某个按钮时用类中的方法更新UILabel的文本。我试图通过MyLabel.text = "text"更改文字,但它给我的错误是'实例成员不能用于类型"查看控制器"'请帮我找一下它的错误并解释一下!非常感谢!这是我的代码:

    class ViewController: UIViewController {

class Door {

    var DoorLocked = false

    func lockDoor() {
        DoorLocked = true
        MyLabel.text = "The door is locked!"
    }

    func unlockDoor() {
        DoorLocked = false
        MyLabel.text = "The door is unlocked!"
    }

    init() {
        MyLabel.text = "This is a door!"
    }
}

var DoorStatus = Door()

@IBOutlet weak var MyLabel: UILabel!

@IBAction func LockButton(sender: AnyObject) {
    DoorStatus.lockDoor()
}

@IBAction func UnlockButton(sender: AnyObject) {
    DoorStatus.unlockDoor()
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

2 个答案:

答案 0 :(得分:1)

内部班级DoorMyLabel一无所知。与其他语言不同,内部类不与它们声明的类共享变量。这是漂亮,就像Door类在顶层ViewController声明一样。你需要更多的背景来分离模型和模型。将ViewController放入单独的类中,然后使它们与协议/委托模式正确通信。除非您按照模板确切了解方法,否则首先只需执行ViewController中的所有内容。因此,请直接在doorLocked内声明模型变量ViewController,并将其更新,并直接在@IBAction内更改标签文字。

再次提醒一下,这只是学习iOS& Swift在基础级别,接下来应该是适当的MVC设计。

此外,所有变量都应以小写字母开头。每次使用大写字母启动变量时,都会伤害眼睛,因为它看起来像是类或其他类型而不是存储。

答案 1 :(得分:1)

从架构的角度来看,我认为Door类知道特定ViewController上的任何标签是没有意义的。此外,Swift语言不允许您在嵌套类中访问该标签。相反,请考虑做类似的事情:

class ViewController: UIViewController {

    class Door {

        var DoorLocked = false

        func lockDoor() {
            DoorLocked = true
        }

        func unlockDoor() {
            DoorLocked = false
        }

    }

    var DoorStatus = Door()

    @IBOutlet weak var MyLabel: UILabel!

    @IBAction func LockButton(sender: AnyObject) {
        DoorStatus.lockDoor()
        MyLabel.text = "The door is locked!"
    }

    @IBAction func UnlockButton(sender: AnyObject) {
        DoorStatus.unlockDoor()
        MyLabel.text = "The door is unlocked!"
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        MyLabel.text = "This is a door!"
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}