this is my first iOS App. I’m using a Modal ViewlController to save new list entries. Unfortunately I can't manage to update the tableView with the new entry afterwards. Here is a screen cast o the current state of the app.
I tried other solutions on stack overflow, but somehow my app always crashes after pressing the Load New Film Button. I recognised, that most user call there Modal ViewController within the code, that doesn't worked for me either.
So I did it in the storyboard: screencast Modal ViewController via segue
Could you help me with reloading the tableView, please?
Here is my code:
This is the main ViewController:
import UIKit
import RealmSwift
class LoadedFilmsTableViewController: UITableViewController {
let realm = try! Realm()
var filmRolls: Results<FilmRoll>?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: K.cellNibNameLoaded, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.CellFilmRoll)
loadFilmRolls()
}
//MARK: - TableView Datasource Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filmRolls?.count ?? 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let df = DateFormatter()
df.dateFormat = "d. MMMM yyyy"
let dateAsString = df.string(from: filmRolls?[indexPath.row].dateLoaded ?? Date())
let cell = tableView.dequeueReusableCell(withIdentifier: K.CellIdentifier.CellFilmRoll, for: indexPath) as! LoadedFilmCell
cell.labelFilmStock.text = filmRolls?[indexPath.row].filmStock ?? "No film roll added yet."
cell.labelCamera.text = filmRolls?[indexPath.row].camera ?? "No film roll added yet."
cell.labelDateLoaded.text = dateAsString
return cell
}
//MARK: - Add new Film Rolls
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
}
func loadFilmRolls() {
filmRolls = realm.objects(FilmRoll.self)
tableView.reloadData()
}
}
This it the Modal View:
import UIKit
import RealmSwift
class AddNewRollViewController: UIViewController {
let realm = try! Realm()
var filmRolls: Results<FilmRoll>?
@IBOutlet weak var textFieldFilmStock: UITextField!
@IBOutlet weak var textFieldCamera: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textFieldFilmStock.placeholder = "Kodak Color Plus 200"
textFieldCamera.placeholder = "Canon AE-1"
}
@IBAction func addNewFilmRollButtonPressed(_ sender: UIButton) {
let newFilmRoll = FilmRoll()
newFilmRoll.filmStock = textFieldFilmStock.text!
newFilmRoll.camera = textFieldCamera.text!
newFilmRoll.dateLoaded = Date()
do {
try realm.write {
realm.add(newFilmRoll)
}
} catch {
print("Error saving FilmRoll \(error)")
}
navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
}
}