我里面有一个 UIViewController 和一个 UIView 。当我尝试在 UIView 内添加警报时,我必须使用控制器来呈现 UIAlertController。如何将 UIViewController 的引用传递给 UIView 类?或者我如何创建控制器的委托?
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。相反,您应该声明委托协议GameBoardUIView
那你的ViewController
采用如下:
// 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)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)