【问题标题】:Swift: Access an enum from another viewController classSwift:从另一个 viewController 类访问枚举
【发布时间】:2018-08-08 01:24:18
【问题描述】:

我有两个视图控制器(A 和 B)。在主视图控制器(A)中,我试图设置一个变量,可能的值是枚举。以下代码在第二个viewcontroller(B)中

代码:

enum Numbers: String {
    case one = "One"
    case two = "two"
    case three = "three"
}

var numberSelected: Numbers? = .one

我正在尝试加载第二个 ViewController(B) 并根据主视图控制器中的选择设置 numberSelected 值:

func loadSecondoViewController() {
    let storyBoard = self.storyboard?.instantiateViewController(withIdentifier: "ColorsViewController")
    guard let secondVC =  storyBoard as? SecondViewController else {return}
    
    secondVC.modalTransitionStyle = UIModalTransitionStyle.flipHorizontal
    switch languageSelected {
    case .one:
        secondVC.numberSelected = secondVC.
        
   self.present(secondVC, animated: true, completion: nil)
}

在这一行:

secondVC.numberSelected = secondVC.

我无法访问数字(枚举)。

有人知道我们如何从主视图控制器中设置 numberSelected 吗?

非常感谢您的帮助。

【问题讨论】:

    标签: ios swift enums xcode9.4


    【解决方案1】:

    您无法访问Numbers,因为嵌套在类中的枚举是static。您不能通过该类的实例访问静态成员。您可以像这样正常访问它:

    secondVC.numberSelected = SecondViewController.Numbers.one
    

    其实你可以这样写:

    secondVC.numberSelected = .one
    

    如果languageSelected的类型也是SecondViewController.Numbers,你可以在一行中做到这一点,不用switch语句:

    secondVC.numberSelected = languageSelected
    

    【讨论】:

      【解决方案2】:

      在任何其他类(如常量类)中创建枚举,并且您想在哪个类中使用枚举只需创建该枚举的对象并与该对象一起使用。

      【讨论】:

      • 你能发帖和例子吗?
      • 这是你的枚举: enum checkUSerType : String{ case kSignUpUser = "signUp" case kLoginUser = "Login" } 在使用类 var userType = checkUSerType.kLoginUser 中创建对象
      • 在另一个类中创建对象或相同的枚举,并从 segue 或对象中设置您想要分配的值 destinationVC.userType = userType == checkUSerType.kSignUpUser ? .kSignUpUser : .kLoginUser
      猜你喜欢
      • 2020-11-04
      • 2015-06-16
      • 2018-01-09
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      相关资源
      最近更新 更多