mvvm - Swift - How to use a closure to fire a function in a view model? -
i watching video series
swift talk #5 connecting view controllers url: https://talk.objc.io/episodes/s01e05-connecting-view-controllers
in video series remove prepareforsegue
, use app
class handle connection between different view controllers.
i want replicate this, in current view model; don't how connect view controllers through view model (or if you're meant to)
in code, @ github: https://github.com/objcio/s01e05-connecting-view-controllers/blob/master/example/appdelegate.swift
they use within view controller
var didselect: (episode) -> () = { _ in }
this runs;
func showepisode(episode: episode) { let detailvc = storyboard.instantiateviewcontrollerwithidentifier("detail") as! detailviewcontroller detailvc.episode = episode navigationcontroller.pushviewcontroller(detailvc, animated: true) }
in same way, want use viewcontroller use viewmodel menu button press (relying on tag).
my code follows;
struct mainmenuviewmodel { enum mainmenutag: int { case newgametag = 0 } func menubuttonpressed(tag: int) { guard let tagselected = mainmenutag.init(rawvalue: tag) else { return } switch tagselected { case .newgametag: print ("pressed new game btn") break } } func menubtndidpress(tag: int) { print ("you pressed: \(tag)") // switch here // go next view controller? should view model know navigation controllers, pushing, etc? } } class mainmenuviewcontroller: uiviewcontroller { @iboutlet var mainmenubtnoutletcollection: [uibutton]! var didselect: (int) -> () = { _ in } override func viewdidload() { super.viewdidload() } @ibaction func mainmenubtnpressed(_ sender: uibutton) { let tag = (sender).tag self.didselect(tag) } }
what don't understand how connect command
self.didselect(tag)
to function
func menubuttonpressed(tag: int)
within viewmodel
as understand it, according swift talk video idea view controller "plain" , view model handles major stuff, menu button presses , moving different view controllers necessary.
how connect didselect item viewmodel function?
thank you.
you should set didselect
property controller here:
func showepisode(episode: episode) { let detailvc = storyboard.instantiateviewcontrollerwithidentifier("detail") as! detailviewcontroller detailvc.episode = episode detailvc.didselect = { episode in // whatever need // example dismiss detailvc self.navigationcontroller.popviewcontroller(animated: true) // or call model methods self.model.menubuttonpressed(episode) } navigationcontroller.pushviewcontroller(detailvc, animated: true) }
Comments
Post a Comment