Goal: Create an "add to favorites" button in a Custom TableViewCell which then saves the list of favorites into UserDefaults such that we can get a tableview of favorites only. (I'm using segmentedControl as the means to filter where libraryFilter = 0
(Plan) / 1 = Tag / 2 = Duration / 3 = Favorite)
jsonErgWorkouts
is the array of workouts from a JSON file which is the basis of the filtering.
This is my what I have coded up.
Custom TableViewCell:
import UIKit
class ErgWorkoutCell: UITableViewCell {
@IBOutlet weak var ergWorkoutTitle: UILabel!
}
In the TableView View Controller
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let selectedGroup = selectedWorkoutGroup(libraryFilter: libraryFilter, jsonErgWorkouts: jsonErgWorkouts, workoutGroupBox: workoutGroupBox)
/// this is cast AS! ErgWorkoutCell since this is a custom tableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "ergWorkoutCell") as! ErgWorkoutCell
cell.ergWorkoutTitle.text = selectedGroup[indexPath.row].title
return cell
}
}
func selectedWorkoutGroup(libraryFilter: Int, jsonErgWorkouts:[workoutList], workoutGroupBox: UITextField) -> [workoutList] {
var selectedGroup = [workoutList]()
if libraryFilter == 0 { // Segmented Control #1 (Plan)
selectedGroup = jsonErgWorkouts.filter { $0.group == workoutGroupBox.text }
/// code for libraryFilter 1(Tag)
/// and libraryFilter 2(Duration)
} else if libraryFilter == 3 {
// Need code here to return the filtered JSON of favorites only
}
return selectedGroup
}