gpt4 book ai didi

ios - Swift - 如何将 View Controller 的引用传递给子 UIView 类?

转载 作者:IT王子 更新时间:2023-10-29 05:35:10 29 4
gpt4 key购买 nike

我在其中有一个 UIViewController 和一个 UIView。当我尝试在 UIView 中添加警报时,我必须使用 Controller 来呈现 UIAlertController。如何将 UIViewController 的引用传递给 UIView 类?或者如何创建 Controller 委托(delegate)?

class GameViewController: UIViewController {
@IBOutlet var gameBoardUIView: GameBoardUIView
...
}

class GameBoardUIView: UIView {
...
func move() {
if !gameBoard.checkNextMoveExist() {
var alert = UIAlertController(title: "Game Over", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Cancel, handler: {(action: UIAlertAction!) in
println("Game Over")
}))
}))
// Following would fail because self is not a UIViewController here
// self.presentViewController(alert, animated: true, completion: nil)
}
}
}

最佳答案

按照 MVC 模式,ViewController 知道它的 View,但 View 不应该知道 ViewController。相反,您应该为您的 ViewController 采用的 GameBoardUIView 声明委托(delegate)协议(protocol),如下所示:

// Delegate protocol declared here
protocol GameBoardUIViewDelegate: class {
func checkIfNextMoveExistsForGameBoardUIView(gameBoardUIView: GameBoardUIView)
}

class GameBoardUIView: UIView {

// GameBoardUIView has a delegate property that conforms to the protocol
// weak to prevent retain cycles
weak var delegate:GameBoardUIViewDelegate?

func move() {
if !gameBoard.checkNextMoveExist() {
delegate?.checkIfNextMoveExistsForGameBoardUIView(gameBoardUIView: self)
}
}

}

// View controller subclass adopts the protocol
class GameViewController: UIViewController, GameBoardUIViewDelegate {

@IBOutlet var gameBoardUIView: GameBoardUIView!

override func viewDidLoad() {
super.viewDidLoad()
gameBoardUIView.delegate = self
}

// Delegte protocol method
func checkIfNextMoveExistsForGameBoardUIView(gameBoardUIView: GameBoardUIView) {

let alert = UIAlertController(title: "Game Over", message: nil, preferredStyle: .alert)

alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: {(action: UIAlertAction!) in
print("Game Over")
}))

// If you need to feed back to the game view you can do it in the completion block here
present(alert, animated: true, completion: nil)
}
}

关于ios - Swift - 如何将 View Controller 的引用传递给子 UIView 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24594238/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com