2015-02-06 57 views
-1

我想知道我們如何通過數據回從彈出的ViewController傳遞數據從彈出的ViewController回用斯威夫特

FirstViewController -----push----> SecondViewController 

SecondViewController -----popped(Pass Value?) ----> FirstViewController 

我尋覓了一圈,發現許多解決方案要求使用委託,但那些在我不熟悉的Objective C中。

我們如何在Swift中做到這一點?

謝謝

+0

鏈接給OBJ-C解決方案的協議實現方法,你發現了什麼? – AstroCB 2015-02-06 03:19:42

+0

@AstroCB http://stackoverflow.com/questions/6203799/dismissmodalviewcontroller-and-pass-data-back – JayVDiyk 2015-02-06 03:20:49

+0

@AstroCB http://stackoverflow.com/questions/14468995/passing-data-back-with-multiple-viewcontrollers -using-delegates – JayVDiyk 2015-02-06 03:21:10

回答

1

其實代表們不只是在客觀C.代表團提供可在斯威夫特(任何不涉及的Objective-C的動態特性能夠在斯威夫特)和授權是一種設計模式( delegation as a design pattern),而不是語言實現。您可以使用兩種方法之一,塊/閉包或委派。在迅速代表團的一個例子蘋果的文檔中找到如下參考:

Apple documentation on delegation

您還可以看到在關閉了蘋果的文檔參考這裏: Apple documentation on closures

可以證明代表團的一個例子下面:

注意,委託通過下面的協議宣稱:

protocol DiceGame { 
    var dice: Dice { get } 
    func play() 
} 
protocol DiceGameDelegate { 
    func gameDidStart(game: DiceGame) 
    func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) 
    func gameDidEnd(game: DiceGame) 
} 

類檢查其是否具有一個委託,如果是這樣,它調用的類必須由符合上述

class SnakesAndLadders: DiceGame { 
     let finalSquare = 25 
     let dice = Dice(sides: 6, generator: LinearCongruentialGenerator()) 
     var square = 0 
     var board: [Int] 
     init() { 
      board = [Int](count: finalSquare + 1, repeatedValue: 0) 
      board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02 
      board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08 
     } 
     var delegate: DiceGameDelegate? 
     func play() { 
      square = 0 
      delegate?.gameDidStart(self)//Calls the method gameDidEnd on the delegate passing self as a parameter 
      gameLoop: while square != finalSquare { 
       let diceRoll = dice.roll() 
       delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll) 
       switch square + diceRoll { 
       case finalSquare: 
        break gameLoop 
       case let newSquare where newSquare > finalSquare: 
        continue gameLoop 
       default: 
        square += diceRoll 
        square += board[square] 
       } 
      } 
      delegate?.gameDidEnd(self)//Calls the method gameDidEnd on the delegate passing self as a parameter 
     } 
    } 
+1

作爲這個答案的一個附註,我非常建議你在Swift之前學習Objective-C。我之所以這麼說是因爲我最近看到了一個人首先學習Swift的趨勢,並且不瞭解Swift和Obj-C之間的API和設計模式沒有什麼不同。你應該能夠閱讀和理解兩者。沿着斯威夫特根的人們似乎對此一無所知(專業上這將會造成更多的傷害而不是好處)。目前,您必須至少了解如何閱讀Obj-C才能爲iOS編程...期間。 – TheCodingArt 2015-02-06 03:30:02

+0

感謝您的好意和答案! – JayVDiyk 2015-02-06 03:50:11