matanm matanm - 2 months ago 14
Swift Question

UITableView cells updates just after restart of app

There's a button in another ViewController, if I press on it, I should see the time when I pressed on the button.

The button works, but the table won't refresh after I click on a refresh button, place the refresh on the ViewDidAppear function doesn't work as well.

I need to quit the app, close it from multitasking and open it again, then the time that I pressed on the button shows. What should I do to make the refresh button work?

(Both View Controllers are in the same storyboard, the second one extends the first one)

First View Controller:

class Tracking: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var activity: UITableView!
var activities = [String]()
var userData = false

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activities.count
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = activities[indexPath.row]
return(cell)
}

@IBAction func Reload(_ sender: AnyObject) {
activity.reloadData()
}
.
.
.
}


Second view controller:

class Activity: Tracking {
.
.
.
@IBAction func playButton(_ sender: AnyObject) {
isPlayed += 1
userData = true
UserDefaults.standard.set(userData, forKey: "userData")
let playElm = playStr + " בשעה: " + getTime()
activities.append(playElm)
UserDefaults.standard.set(activities, forKey: "activities")
}
.
.
.
}

Answer Source

You need to fetch from user defaults your new date in activities array and after that you can reloadData

@IBAction func Reload(_ sender: AnyObject) {
    self.activities = UserDefaults.standard.get( forKey: "activities")
    activity.reloadData()
}