2016-09-25 71 views
2

我已經從下到上閱讀了this thread(以及類似的其他),但它根本不符合我的需求。Swift /如何使用popViewController調用委託

我有一個UIViewController裏面UIPageViewControllerUINavigationController內。導航到第二個ViewController。導航到第三個ViewController並想回到第二個ViewController傳遞數據。

我當前的代碼:

protocol PassClubDelegate { 
      func passClub(passedClub: Club) 
     } 

class My3rdVC: UIViewController { 

     var clubs: [Club] = [] 

     var passClubDelegate: PassClubDelegate? 

.... 

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 

     let club = clubs[indexPath.row] 
     self.passClubDelegate?.passClub(club) 
     navigationController?.popViewControllerAnimated(true) 
    } 

我的第二個VC:

class My2ndVC: UIViewController, PassClubDelegate { 

    var club = Club() 

    func passClub(passedClub: Club) { 

     SpeedLog.print("passClub called \(passedClub)") 
     club = passedClub 
    } 

passClub不叫。我確定這是因爲我沒有將代理設置爲My2ndVC,但我該怎麼做?我找到的所有解決方案都希望我使用a)segue或b)實例化一個My2ndVC new,它沒有任何意義,因爲它仍然在內存中,我想彈回來重新回到層次結構中。我錯過了什麼?我有什麼可能?非常感謝幫助。

PS:我沒有使用任何segues。 My3rdVC被稱爲是:

let vc = stb.instantiateViewControllerWithIdentifier("My3rdVC") as! My3rdVC 
self.navigationController?.pushViewController(vc, animated: true) 

回答

3

您可以在My2ndVCprepareForSegue方法設置的My3rdVC委託。

class My2ndVC: UIViewController, PassClubDelegate { 

    ... 

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 

     super.prepareForSegue(segue, sender: sender) 

     switch segue.destinationController { 
     case let controller as My3rdVC: 
      controller.passClubDelegate = self 
     } 
    } 
} 

這是假設你已經在你的故事板,從My2ndVCMy3rdVC到導航控制器棧,我假設你已經創建了一個SEGUE。所以試試把這個prepareForSegue方法粘貼到My2ndVC,看看它是否有效。

UPDATE

let vc = stb.instantiateViewControllerWithIdentifier("My3rdVC") as! My3rdVC 

vc.passClubDelegate = self 

navigationController?.pushViewController(vc, animated: true) 
+0

我沒有使用任何塞格斯。 –

+0

但當然,爲你的努力upvote。謝謝 –

+0

你可以在實例化My3rdVC之後傳遞委託,但在把它推到導航控制器堆棧 – Callam