【问题标题】:Pass data back from a popped ViewController using Swift使用 Swift 从弹出的 ViewController 传回数据
【发布时间】:2015-02-06 03:18:07
【问题描述】:

我想知道我们如何从弹出的 ViewController 传回数据

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

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

我四处搜索并找到了许多要求使用委托的解决方案,但这些都是我不熟悉的 Objective C 中的。

我们如何在 Swift 中做到这一点?

谢谢

【问题讨论】:

标签: ios xcode swift


【解决方案1】:

实际上委托不仅仅在 Objective C 中可用。委托在 Swift 中可用(任何不涉及 Objective-C 动态特性的东西都可以在 Swift 中使用)并且委托是一种设计模式 (delegation as a design pattern),而不是语言实现。您可以使用两种方法之一,即块/闭包或委托。可以在此处引用的 Apple 文档中找到 swift 委派的示例:

Apple documentation on delegation

您还可以在此处查看有关 Apple 闭包文档的参考资料: 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
        }
    }

【讨论】:

  • 作为这个答案的附注,我强烈建议您在 Swift 之前学习 Objective-C。我之所以这么说,是因为我最近看到人们首先学习 Swift 并且不理解 Swift 和 Obj-C 之间的 API 和设计模式没有什么不同的趋势。您应该能够阅读并理解两者。使用 Swift 根源的人似乎对此一无所知(从专业上讲,这弊大于利)。目前,您必须至少了解如何阅读 Obj-C 来为 iOS 编程......时期。
  • 感谢您的友好建议和回答!
猜你喜欢
  • 1970-01-01
  • 2014-10-13
  • 2017-11-08
  • 1970-01-01
  • 2016-01-05
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多