2017-07-25 18 views
0

我看視頻系列Swift - 如何使用閉包在視圖模型中觸發一個函數?

斯威夫特談#5 連接視圖控制器 網址:https://talk.objc.io/episodes/S01E05-connecting-view-controllers

在這個系列影片,他們刪除所有prepareForSegue,並使用App類來處理不同的視圖控制器之間的連接。

我想複製這個,但具體只在我目前的視圖模型;但我不明白的是如何視圖控制器通過視圖模型連接(或者即使你意思)

在他們的代碼,在github上:https://github.com/objcio/S01E05-connecting-view-controllers/blob/master/Example/AppDelegate.swift

他們用自己的視野內做到這一點控制器

var didSelect: (Episode) ->() = { _ in }

此運行;

func showEpisode(episode: Episode) { 
     let detailVC = storyboard.instantiateViewControllerWithIdentifier("Detail") as! DetailViewController 
     detailVC.episode = episode 
     navigationController.pushViewController(detailVC, animated: true) 
    } 

以同樣的方式,我想用我的ViewController來使用我的ViewModel的菜單按鈕按(依靠標籤)。

我的代碼如下;

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)") 
     // Do a switch here 
     // Go to the next view controller? Should the view model even know about 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) 

    } 
} 

我不明白的是我怎麼命令

self.didSelect(tag)

連接功能

func menuButtonPressed(tag: Int)

內我的ViewModel

正如我理解它,一致視頻控制器是「普通」的,視圖模型處理所有主要內容,如菜單按鈕按下,然後根據需要移動到不同的視圖控制器。

如何將didSelect項目連接到我的viewModel函數?

謝謝。

回答

1

您應該設置didSelect屬性控制器喜歡這裏:

func showEpisode(episode: Episode) { 
    let detailVC = storyboard.instantiateViewControllerWithIdentifier("Detail") as! DetailViewController 
    detailVC.episode = episode 
    detailVC.didSelect = { episode in 
     // do whatever you need 
     // for example dismiss detailVC 
     self.navigationController.popViewController(animated: true) 
     // or call the model methods 
     self.model.menuButtonPressed(episode) 
    } 
    navigationController.pushViewController(detailVC, animated: true) 
} 
相關問題