Ios 如何在没有segue和故事板编程的情况下传递数据?

Ios 如何在没有segue和故事板编程的情况下传递数据?,ios,iphone,swift,uiviewcontroller,Ios,Iphone,Swift,Uiviewcontroller,我想将数据从vc1传递到vc2 vc1有许多按钮。 vc2有很多元素,检测用户按下哪个按钮显示不同的元素。 因此,我只编写了两个.swift文件来更改不同的UI vc1: vc2: 打印数据为空。 我该如何处理这个想法呢?在vc1中尝试一下 let vc2 = UIStoryboard(name: "storeyBoardID", bundle: nil).instantiateViewController(withIdentifier: "stroyboardIdOfcontroller")

我想将数据从vc1传递到vc2

vc1有许多按钮。 vc2有很多元素,检测用户按下哪个按钮显示不同的元素。 因此,我只编写了两个.swift文件来更改不同的UI

vc1:

vc2:

打印数据为空。 我该如何处理这个想法呢?

在vc1中尝试一下

 let vc2 = UIStoryboard(name: "storeyBoardID", bundle: nil).instantiateViewController(withIdentifier: "stroyboardIdOfcontroller") as? viewController2

和vc2声明数据变量,如下所示

var data:NSString?

希望这能帮助你

这个问题看起来好像你没有初始化vc2,所以我给你写了一个例子,它对我有用

    @IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func buttonClick(_ sender: UIButton) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc2 = storyboard.instantiateViewController(withIdentifier :"vc2") as! vc2
    switch sender {

    case button1:
        vc2.data = "name"
        present(vc2, animated: true, completion: nil)
        break

    case button2:
        vc2.data = "photo"
        present(vc2, animated: true, completion: nil)
        break

    default:
        print("default")

}
}
和vc2

    var data:NSString = ""


override func viewDidLoad() {
    super.viewDidLoad()

    print("data is here : \(data)")

    switch data {

    case "name":
        print("here is button1View")
        break
    case "photo":
        print("here is button2View")
        break
    default:
        print("default View")
    }

}

你又有什么问题?什么不起作用?var data:NSString=,这是错误的,请将其写为var data:NSString?在当前场景中,您正在初始化数据变量。如何传递数据?将代码从viewDidLoad移动到ViewWillAppear为什么不为VC2添加一个初始方法并将数据作为参数传递。例如initdata:NSData?
var data:NSString?
    @IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func buttonClick(_ sender: UIButton) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc2 = storyboard.instantiateViewController(withIdentifier :"vc2") as! vc2
    switch sender {

    case button1:
        vc2.data = "name"
        present(vc2, animated: true, completion: nil)
        break

    case button2:
        vc2.data = "photo"
        present(vc2, animated: true, completion: nil)
        break

    default:
        print("default")

}
}
    var data:NSString = ""


override func viewDidLoad() {
    super.viewDidLoad()

    print("data is here : \(data)")

    switch data {

    case "name":
        print("here is button1View")
        break
    case "photo":
        print("here is button2View")
        break
    default:
        print("default View")
    }

}