2016-08-11 112 views
0

我使用instantiateViewControllerWithIdentifier(identifier: String)函數從ViewControllerA創建ViewControllerB的實例。如何使用swift將數據從viewcontroller A傳遞到另一個viewcontroller 3

let storyboard = UIStoryboard(name: "Main", bundle: nil) 
let vc = storyboard.instantiateViewControllerWithIdentifier("vcB") as VCB; 
rootController!.presentViewController(vc, animated: true, completion: nil) 


class VCB: UIViewController { 

required init?(coder aDecoder: NSCoder){ 
    super.init(coder: aDecoder) 
    } 

} 

我想訪問我已經在我的ViewControllerB中傳遞的值我怎麼能實現這一點。

我已經通過了 Passing Data between View Controllers鏈接,但在目標c中的答案。

+1

有很多方法,你可以從一個視圖控制器將數據傳遞到另一個視圖 - 控制喜歡使用NSNotification中心,委託,PrepareforSegue,並使用對propertyList –

+0

您鏈接的問題有很多答案,斯威夫特也。 – rmaddy

回答

1

你只可以在你的VCB的viewController聲明var和注入數據到這個屬性

let storyboard = UIStoryboard(name: "Main", bundle: nil) 
let vc = storyboard.instantiateViewControllerWithIdentifier("vcB") as VCB; 

vc.yourData = SOME_DATA 

rootController!.presentViewController(vc, animated: true, completion: nil) 


class VCB: UIViewController { 

var yourData: AnyObject? 

required init?(coder aDecoder: NSCoder){ 
    super.init(coder: aDecoder) 
    } 

} 
+0

我必須在viewcontrollerA中導入我的viewcontrollerB嗎? –

+1

@Ashok不,你不需要。 – Rishab

+2

不,你不需要 – iSashok

3

您可以嘗試

import UIKit 
class ViewControllerA: UIViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
} 

@IBAction func passDataAction(sender: AnyObject) { 
    let storyboard = UIStoryboard(name: "Main", bundle: nil) 
    let vc = storyboard.instantiateViewControllerWithIdentifier("UIViewControllerB") as! ViewControllerB; 
    vc.dataFromOtherView = "The data is passed" 
    self.presentViewController(vc, animated: true, completion: nil) 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

} 

而其他類

import UIKit 
class ViewControllerB: UIViewController { 

var dataFromOtherView: String = "" 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    print(dataFromOtherView) 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


} 
+0

從哪裏我必須調用passDataAction方法 ? –

1

剛使用此代碼從一個視圖con發送數據troller到anotherview控制器

let storyboard = UIStoryboard(name: "Main", bundle: nil) 
let vc=storyboard.instantiateViewControllerWithIdentifier("secondView") as! ViewControllerB; 
vc.dataFromOtherView = "The data is passed" 
self.presentViewController(vc, animated: true, completion: nil) 
相關問題