使用Swift从popup的ViewController传回数据
我想知道如何从popup的ViewController传回数据
FirstViewController -----push----> SecondViewController SecondViewController -----popped(Pass Value?) ----> FirstViewController
我已经四处search,发现了许多要求使用代表的解决scheme,但是那些在Objective C中我不熟悉。
我们如何在Swift中做到这一点?
谢谢
实际上,委托并不仅仅在Objective C中可用。委托在Swift中可用(任何不涉及Objective-C的dynamic特性的都可以在Swift中实现),委托是devise模式( 委托作为devise模式 ),而不是语言实现。 您可以使用两种方法之一,块/closures或委派。 在swift中委托的例子可以在苹果的文档中find,如下所示:
苹果关于授权的文件
您也可以在这里看到有关Apple关于closures的文档的参考资料: 关于closures的Apple文档
下面显示了一个授权的例子:
注意到代表是通过下面的协议声明的:
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 } }