如何访问枚举中的变量?

时间:2015-03-28 14:31:20

标签: ios swift enums

class DetailsViewController: UIViewController
{
    @IBOutlet weak var summaryButton: UIBarButtonItem!
    @IBOutlet weak var commentaryButton: UIBarButtonItem!   
    enum viewState: Int {
        case summary
        case commentary

        func setVisibility() {
            switch (self) {
                case summary:
                    summaryButton.enabled = true
                    commentaryButton.enabled = false
                case commentary:
                    summaryButton.enabled = false
                    commentaryButton.enabled = true
            }
        }
    }
}

我无法访问summaryButton和commentaryButton:提供错误说" DetailsViewController.type没有名为summaryButton的成员"

如何访问summaryButton和commentaryButton?

解决方案:这对我有用

enum viewState {
case Summary
case Commentary    
}

class DetailsViewController: UIViewController
{
@IBOutlet weak var summaryButton: UIBarButtonItem!
@IBOutlet weak var commentaryButton: UIBarButtonItem!

var currentState: viewState = .Summary {
    didSet {
        switch (currentState) {
        case .Summary:

            summaryButton.enabled = true
            commentaryButton.enabled = false
            break
        case .Commentary:
            summaryButton.enabled = false
            commentaryButton.enabled = true
            break
        default:
            break

        }
    }
}

1 个答案:

答案 0 :(得分:0)

在我看来,你的解决方案是倒退的。让enum拥有自己的IBOutlets按钮很奇怪。

我会将枚举和setVisibility方法移到枚举之外并进入DetailsViewController。在DetailsViewController中创建一个类型为viewState的实例变量currentViewState,然后根据currentViewState使setVisibility方法切换。