使用相同的全局变量实例化多个viewcontroller

时间:2019-02-22 14:19:31

标签: ios swift uiviewcontroller

我如何从一个具有某些类似变量的视图控制器列表中声明一个视图控制器,而无需重复自己和而不创建基本的视图控制器?像这样:

let storyboard = UIStoryboard(name: "MainStoryboard", bundle: nil)

swtich(type){
  case "A":
    vcGeneric = storyboard.instantiateViewController(withIdentifier: "TypeAViewController") as! TypeAViewController
    break;
  case "B":
    vcGeneric = storyboard.instantiateViewController(withIdentifier: "TypeBViewController") as! TypeBViewController
    break;
}
vcGeneric.variableSame1 = "SomeValue1"
vcGeneric.variableSame2 = "SomeValue2"
vcGeneric.variableSame3 = "SomeValue3"
self.present(vcGeneric, animated: true, completion: nil)

我通过声明var vcGeneric: UIViewController进行了尝试,但收到编译错误Value of type "UIViewController" has no member "variableSame1"

1 个答案:

答案 0 :(得分:3)

使用协议定义通用属性,如下所示:

protocol CommonViewController {
    var variableSame1: String? { get set }
    var variableSame2: String? { get set }
    var variableSame3: String? { get set }
}

class ViewController1: UIViewController, CommonViewController {
    var variableSame1: String?
    var variableSame2: String?
    var variableSame3: String?
}
class ViewController2: UIViewController, CommonViewController {
    var variableSame1: String?
    var variableSame2: String?
    var variableSame3: String?
}
class ViewController3: UIViewController, CommonViewController {
    var variableSame1: String?
    var variableSame2: String?
    var variableSame3: String?
}

let storyboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
var type = "A"
var vcGeneric: CommonViewController?
switch type {
case "A":
    vcGeneric = storyboard.instantiateViewController(withIdentifier: "TypeAViewController") as! ViewController1
    break;
case "B":
    vcGeneric = storyboard.instantiateViewController(withIdentifier: "TypeBViewController") as! ViewController2
    break;
default:
    vcGeneric = storyboard.instantiateViewController(withIdentifier: "TypeCViewController") as! ViewController3
    break;
}
vcGeneric.variableSame1 = "SomeValue1"
vcGeneric.variableSame2 = "SomeValue2"
vcGeneric.variableSame3 = "SomeValue3"
self.present(vcGeneric, animated: true, completion: nil)