Reusable UITableView for Varying Data Input - Swift/Xcode

82 Views Asked by At

I have a TableView that I want to reuse for different categories of data (essentially as plugins.. the tableView being a skeleton and being filled with whatever I want it to be). The TableView is filled with different categories of data (and related actions) depending on essentially what ViewController the user came from. I understand how to make it display the various data (just send it whatever array I want it to display), but I can't figure out how I could control the actions for the data at the specific index selected in didSelectRowAtIndexPath.

How could I do this? How could I create an array that has both Strings and executable actions associated with each indices? For example:

arrayOneNames = ["Tigris", "Leo", "Barko"]
arrayOneActions = [displayTheTigers, displayTheCats, displayTheDogs]

If "Leo" is selected in the tableView, then "displayTheCats" is executed. Again, I want each array to be a separate Class that I can use as a plugin, so that I can fill the tableView with whichever Class of data I want it to display and execute, depending on which ViewController the user came from previously. Please answer in Swift.

1

There are 1 best solutions below

0
Wimukthi Rajapaksha On
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell=UITableViewCell() // cell you've created
    cell.data = arrayOneNames[indexPath.row] // passing relevant data
    cell.tag = indexPath.row // the tag you want to pass for particular data 
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)! as UITableViewCell // take selected cell
    if(cell.tag == 0) { // call relevant function accordingly.
        self.tigrisTouch()
    } else if (cell.tag == 1) {
        self.leoTouch()
    } else {
        self.barkoTouch()
    }
}

private func tigrisTouch() {
}

private func leoTouch() {        
}

private func barkoTouch() {
}