Sh4rP EYE Sh4rP EYE - 7 months ago 21
Swift Question

Calling a function/passing data from outside a TableViewController (and others) in Swift

In my app I have one screen divided between two ViewControllers - LadderViewController and GameHistoryTableViewController, which lies in a container. I want user to be able to filter the data in the table by tapping on something in the LadderView. I tried to solve this using delegates:

LadderViewController:

delegate = GameHistoryTableViewController()
func imageTapped(imageIndex: Int) {
delegate?.selectedHeroNumber(imageIndex)
}


GameHistoryTableViewController: (conforms to the delegate protocol and implemets a function from it)

func selectedHeroNumber(heroNumber: Int) {
let filteredGames = filterGamesFromHeroNumber(heroNumber)
tableDataSource = filteredGames
self.tableView.reloadData()
}


That doesn't work, though, because the delegate I declare in LadderViewConroller is another instance of GameHistoryTableViewController, not the (to the user) shown one. I don't know how to access the "visible" instance (table) of GameHistoryTableViewController though... So, how should be delegating used here? Or should I use another approach (and if so, what kind)? I basically need to change the table's data source according to on what the user taps, one can say "from outside" (dataSource is a property in my GameHistoryTableViewController class).

Answer

There are a few ways to achieve this, I have a similar setup for which I use a model class with a singleton to store the relevant data.

For instance you could have the following

class dataModel {

  static let sharedInstance = dataModel()

  private var _heroNumber = Int()

private init() {}

  var heroNumber: Int = {

    return _heroNumber

  }

  func setHero(hero: Int) -> Int {

    return _heroNumber

  }
 }
}

You can then can access this model from each of your controllers using dataModel.sharedInstance.heroNumber etc...

Comments