I have a UIViewController and a UIView inside it. When I try to add an alert inside the UIView, I have to use the controller to present the UIAlertController. How do I pass the reference of UIViewController to the UIView class? Or alternatively how do I create a delegate of controller?
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)
}
}
}
Following the MVC pattern, a ViewController knows about its Views, but the View shouldn't know about the ViewController. Instead you should declare delegate protocol for
GameBoardUIView
that yourViewController
adopts as follows:alternatively, you can also post notifications from your .xib and have the parent viewcontroller observes it. you will be able to send data via userInfo object during the posting.