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

Swift 2: Instance Member cannot be used on type "View Controller"

我是 swift 的新手,我正在试验 classes 和方法!我一直在寻找 google 和 Whosebug 来寻找答案!我已经阅读了多个具有相同问题的帖子,但它们仍然没有帮助我!我已经为一个更大的应用程序编写了 swift 代码,但决定编写一小部分,所以我也有同样的想法。当按下某个按钮时,我试图用 class 中的方法更新 UILabel 的文本。我试图通过 MyLabel.text = "text" 更改文本,但它给我错误 'Instance member cannot be used on type "view controller"' 请帮我找出问题所在并解释它!太感谢了!下面是我的代码:

    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.
}

}

内在的classDoorMyLabel一无所知。与其他语言不同,内部 classes 不与声明它们的 class 共享变量。它 漂亮 很像 Door class 在顶层与 ViewController 一起声明。您需要更多背景知识才能将模型和 ViewController 分成单独的 classes,然后使它们与 protocol/delegate 模式正确通信。除非您完全按照模板进行操作,否则首先只需在 ViewController 内完成所有操作。因此,直接在 ViewController 中声明您的模型变量 doorLocked,并在 @IBAction.

中直接更改标签文本的同时更新它

再次提醒,这只是在基础水平上学习 iOS 和 Swift,接下来应该进行适当的 MVC 设计。

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

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

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.
    }
}