2017-07-26 116 views
0

我有主視圖控制器連接到2視圖控制器。 我做了協議,我有didRecive(數據:數據)委託功能。代表多個視圖控制器

protocol MainViewControllerDelegate: class { 
func didReciveDepartment(response:DepartmentResponse) 

}

在主視圖控制器我聲明代表變種。

weak var delegate: DepartmentMainViewControllerDelegate? 

在爲segue做準備時,我將此代理設置爲viewCotnroller's。像這樣 -

 if segue.identifier == "productsEmbedded" { 
     let vc = segue.destination as! DepartmentProductsViewController 
     delegate = vc 


    } 
    if segue.identifier == "shopsEmbedded" { 
     let vc = segue.destination as! DepartmentShopsViewController 
     vc.delegate = self 
     delegate = vc 
    } 

我了有線的行爲僅代表觸發DepartmentShopsViewController,並DepartmentProductsViewController不能得到這個委託,我註釋掉商店和產品得到這個delgate所以這意味着我不能使用相同的委託2控制器?

+0

....你怎麼能保存同一個變量 – radkrish

+0

只是做第二次代表VAR兩個對象,並沒有奏效。 –

+0

'productsEmbedded' segue中的'delegate = vc'是什麼? – Subramanian

回答

0

加油的人,你忘記了線

vc.delegate = self   

的代碼看起來應該是這樣

if segue.identifier == "productsEmbedded" { 
    let vc = segue.destination as! DepartmentProductsViewController 
    vc.delegate = self  //Add this Line 
    delegate = vc 
} 
if segue.identifier == "shopsEmbedded" { 
    let vc = segue.destination as! DepartmentShopsViewController 
    vc.delegate = self 
    delegate = vc 
} 
+0

錯誤,檢查問題我有一個控制器中的所有這些東西的委託觸發器。和DepartmentsShops vc.delgate,因爲我有DepartmentShopsDelegatei這是一個不同的故事。 –

1

這些都是許多方法來對象之間傳遞消息。您可以使用Delegate和使用NSNotificationCentre傳遞數據。主要區別在於代表,一個指定對象收到一條消息,任何數量的對象在發佈時都會收到通知。 你可以檢查this以前的問題的細節。

+0

錯誤,這兩個視圖控制器作爲容器連接到main,並且當MainViewController被inited時,我只使用preapreForSegue一次。在那裏我設置這些代表,並從這些視圖控制器的代表向主控制器建立它們之間的通信。 –

+0

好吧,我得到你。我將更新我的答案。 – luckyShubhra

+0

澄清我如何在MainViewController中獲取數據? – luckyShubhra

0

對於代表你要實現這樣的

//Declare protocol 
protocol MainViewControllerDelegate { 
    func didReciveDepartment(response:DepartmentResponse) 
} 

class DepartmentProductsViewController: UIViewController { 

    // MARK: - Variable Declaration. 
    var delegate: MainViewControllerDelegate? 

} 

class DepartmentShopsViewController: UIViewController { 

    // MARK: - Variable Declaration. 
    var delegate: MainViewControllerDelegate? 

} 

class MainViewController: UIViewController, MainViewControllerDelegate { 

    //Push ViewController with segue and use delegate property 
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     if segue.identifier == "productsEmbedded"{ 

      let vc = segue.destination as! DepartmentProductsViewController 
      vc.delegate = self 
     } else if segue.identifier == "shopsEmbedded" { 

      let vc = segue.destination as! DepartmentShopsViewController 
      vc.delegate = self 
     } 
    } 

    //MARK: Implement MainViewControllerDelegate Methods. 
    func didReciveDepartment(response: DepartmentResponse) { 

    } 

} 
你想有一個獨立的變量
+0

此代碼不會編譯 –

+0

有任何錯誤 –