Unable to get my "Save" Button to work, my button does nothing when pressed - ios

I'm trying to make a note taking app, however, I'm kinda stuck on how to get my save button to work. Here's what I've got so far:
My Add "Item" View
class AddViewController: UIViewController {
#IBOutlet var addShortDescription: UITextField!
#IBOutlet var addLongDescription: UITextView!
public var completion: ((String, String) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
addShortDescription.becomeFirstResponder()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .done, target: self, action: #selector(didTapSave))
self.title = "Add New Item"
}
#IBAction func didTapSave(_ sender: Any) {
if let text = addShortDescription.text, !text.isEmpty, !addLongDescription.text.isEmpty {
completion?(text, addLongDescription.text)
}
}
}
My Main View
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var table: UITableView!
var models: [(ShortDescription: String, LongDescription: String)] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
table.delegate = self
table.dataSource = self
self.title = "Inventory"
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = models[indexPath.row].ShortDescription
cell.detailTextLabel?.text = models[indexPath.row].LongDescription
return cell
}
#IBAction func addNewInventory(){
guard let vc = storyboard?.instantiateViewController(identifier: "add") as? AddViewController else {
return
}
vc.title = "Add New Item"
vc.navigationItem.largeTitleDisplayMode = .never
vc.completion = { addShortDescription, addLongDescription in
self.navigationController?.popToRootViewController(animated: true)
self.models.append((ShortDescription: addShortDescription, LongDescription: addLongDescription))
self.table.isHidden = false
self.table.reloadData()
}
navigationController?.pushViewController(vc, animated: true)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let model = models[indexPath.row]
// Show addLongDescription controller
guard let vc = storyboard?.instantiateViewController(identifier: "inventory") as?
EditViewController else {
return
}
vc.navigationItem.largeTitleDisplayMode = .never
vc.title = "Edit Item"
vc.addShortDescription.text = model.ShortDescription
vc.addLongDescription.text = model.LongDescription
navigationController?.pushViewController(vc, animated: true)
}
}
I have another view where I plan on allowing the user to edit the added items, I'll add that if you think it may be causing some problems.

Related

How to make the deleteTask method work properly?

I am trying to create a ToDoList in swift UI and my deleteTask function is not working properly. I tried a lot of things and none of them worked.
import UIKit
class ViewController: UIViewController {
#IBOutlet var tableView: UITableView!
var toDoTasks = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "SAVED TASKS"
tableView.delegate = self
tableView.dataSource = self
// setup
if !UserDefaults().bool(forKey: "setup")
{
UserDefaults().set(true, forKey: "setup")
UserDefaults().set(0, forKey: "count")
}
updateTasks()
}
func updateTasks()
{
toDoTasks.removeAll()
guard let count = UserDefaults().value(forKey: "count") as? Int else
{
return
}
for x in 0..<count
{
if let task = UserDefaults().value(forKey: "task_\(x+1)") as? String
{
toDoTasks.append(task)
}
}
tableView.reloadData()
}
#IBAction func didTapAdd()
{
let viewController = storyboard?.instantiateViewController(withIdentifier: "entry") as! EntryViewController
viewController.title = "NEW TASK"
viewController.updated =
{
DispatchQueue.main.async {
self.updateTasks()
}
}
navigationController?.pushViewController(viewController, animated: true)
}
}
extension ViewController: UITableViewDelegate
{
// function to select the rows
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let viewController = storyboard?.instantiateViewController(withIdentifier: "task") as! TasksViewController
viewController.title = "NEW TASK"
viewController.task = toDoTasks[indexPath.row]
navigationController?.pushViewController(viewController, animated: true)
}
}
extension ViewController: UITableViewDataSource
{
// function which returns number of tasks
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toDoTasks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = toDoTasks[indexPath.row]
return cell
}
}
import UIKit
class TasksViewController: UIViewController {
#IBOutlet var label : UILabel!
var task : String?
var currentPosition: Int?
override func viewDidLoad() {
super.viewDidLoad()
label.text = task
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Delete", style: .done, target: self, action: #selector(deleteTask))
}
#objc func deleteTask(_ sender: UIBarButtonItem) {
guard let currentPosition = self.currentPosition else {
return
}
let count = UserDefaults.standard.integer(forKey: "count")
UserDefaults.standard.removeObject(forKey: "task_\(currentPosition+1)")
for i in currentPosition+1..<count {
let task = UserDefaults.standard.string(forKey: "task_\(i+1)")
UserDefaults.standard.setValue(task, forKey: "task_\(i)")
}
UserDefaults.standard.setValue(count-1, forKey: "count")
navigationController?.popViewController(animated: true)
}
}
When I press the Delete button, nothing happens. Could you please help me??

Is there a way to get the id of a UITableViewCell?

my problem: I want to open some kind of Profil if a user pushes a Button in a Table-View Cell. The Cells Data is downloaded from Parse.
The idea is based on Instagram, if you click on the username-button on Insta the profile from the user who posted the image will open. I want to create the same code, but i can't create the code to get the user. Can you help me?
Heres some code:
import UIKit
import Parse
class HomeController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let reuseIdentifer = "FeedCell"
var delegate: HomeControllerDelegate?
var newCenterController: UIViewController!
let tableView = UITableView()
//Für Parse:
var users = [String: String]()
var comments = [String]()
var usernames = [String]()
var lastnames = [String]()
var imageFiles = [PFFileObject]()
var wischen: UISwipeGestureRecognizer!
var wischen2: UISwipeGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
getData()
configureNavigationBar()
configurateTableView()
wischen = UISwipeGestureRecognizer()
wischen.addTarget(self, action: #selector(handleMenuToggle))
wischen.direction = .right
wischen.numberOfTouchesRequired = 1
view.addGestureRecognizer(wischen)
wischen2 = UISwipeGestureRecognizer()
wischen2.addTarget(self, action: #selector(handleMenuToggle))
wischen2.direction = .left
wischen2.numberOfTouchesRequired = 1
view.addGestureRecognizer(wischen2)
}
#objc func handleMenuToggle() {
delegate?.handleMenuToggle(forMenuOption: nil)
}
#objc func showProfile() {
let vc: AProfileViewController!
vc = AProfileViewController()
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)
}
func configureNavigationBar() {
navigationController?.navigationBar.barTintColor = .darkGray
navigationController?.navigationBar.barStyle = .black
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont(name: "Noteworthy", size: 22)!, NSAttributedString.Key.foregroundColor: UIColor.white]
//navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
navigationItem.title = "Mobile Job Board"
navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_menu_white_3x").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleMenuToggle))
navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_mail_outline_white_2x").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(showCreateNewArticle))
}
//MARK: Table View
//skiped table view configuration
}
// - MARK: Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifer, for: indexPath) as! FeedCell
imageFiles[indexPath.row].getDataInBackground { (data, error) in
if let imageData = data {
if let imageToDisplay = UIImage(data: imageData) {
cell.postImage.image = imageToDisplay
}
}
}
cell.descriptionLabel.text = comments[indexPath.row]
cell.userButton.setTitle("\(usernames[indexPath.row]) \(lastnames[indexPath.row])", for: UIControl.State.normal)
cell.userButton.addTarget(self, action: #selector(showProfile), for: .touchUpInside)
return cell
}
//skiped
}
Thanks a lot!
Tom
The issue here is that your button works on a selector and it has no idea about the sender or where it was called from.
I would do this by creating a custom table view cell (e.g. FeedCell) which allows you to set a delegate (e.g. FeedCellDelegate). Set your class as the delegate for the cell and pass into the cell it's current indexPath. You can then return the indexPath in the delegate call.
Example: Note that code has been removed for simplicity and this code has not been tested. This is simply to guide you in the right direction.
View Controller
import UIKit
class HomeController: UIViewController {
// stripped additional information for example
func showProfile(_ username: String) {
let vc: AProfileViewController!
vc = AProfileViewController()
vc.username = username
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)
}
}
extension HomeController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifer, for: indexPath) as! FeedCell
cell.delegate = self
cell.descriptionLabel.text = comments[indexPath.row]
cell.userButton.setTitle("\(usernames[indexPath.row]) \(lastnames[indexPath.row])", for: UIControl.State.normal)
cell.setIndex(indexPath)
return cell
}
}
extension HomeController: FeedCellDelegate {
func didPressButton(_ indexPath: IndexPath) {
let userName = usernames[indexPath.row]
showProfile(username)
}
}
Feed Cell
import UIKit
protocol FeedCellDelegate {
didPressButton(_ indexPath: IndexPath)
}
class FeedCell: UICollectionViewCell {
var delegate: FeedCellDelegate?
var indexPath: IndexPath
#IBOutlet weak var userButton: UIButton
setIndex(_ indexPath: IndexPath) {
self.indexPath = indexPath
}
#IBAction userButtonPressed() {
if(delegate != nil) {
delegate?.didPressButton(indexPath)
}
}
}
You can generically and in a type safe way get the parent responder of any responder with:
extension UIResponder {
func firstParent<T: UIResponder>(ofType type: T.Type ) -> T? {
return next as? T ?? next.flatMap { $0.firstParent(ofType: type) }
}
}
So:
Get the parent tableviewCell of your button in the target action function
Ask your tableview for the index path
Use the index path.row to index into your users array:
#objc func showProfile(_ sender: UIButton) {
guard let cell = firstParent(ofType: UITableViewCell.self),
let indexPath = tableView.indexPath(for: cell) else {
return
}
let user = users[indexPath.row]
... do other stuff here ...
}

how to change navigation bar title according to uitableview row selection?

I've added a navigation bar on my view controller. But when I run my code, this line: let cell = sender as! UITableViewCell has problems. Any idea how I can add or change the navigation bar title according to my selection? My UITableView is a list of array.
Although build successfully, it kept showing me
Thread 1: signal SIGABRT
Besides that, how do I change the navigation bar title according to my selection in the UITableView?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is DetailVC {
let destination = segue.destination as! DetailVC
let cell = sender as! UITableViewCell
destination.navigationItem.title = cell.textLabel?.text
destination.developer = developerArray[(myTableView.indexPathForSelectedRow?.row)!]
myTableView.deselectRow(at: myTableView.indexPathForSelectedRow!, animated: true)
}
}
VIEW CONTROLLER CODE
import UIKit
class Developers {
var developerName: String?
var developerEmail: String?
var developerBalance: Float?
var developerHP: String?
init(dvName: String, dvHP: String) {
self.developerName = dvName
self.developerHP = dvHP
}
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var myTableView: UITableView!
var developerArray = [Developers]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//navigationItem.searchController = UISearchController(searchResultsController: nil)
let developer = Developers(dvName: "Developer 0", dvHP: "Phone Number: #0")
developerArray.append(developer)
let developer1 = Developers(dvName: "Developer 1", dvHP: "Phone Number: #1")
developerArray.append(developer1)
let developer2 = Developers(dvName: "Developer 2", dvHP: "Phone Number: #2")
developerArray.append(developer2)
let developer3 = Developers(dvName: "Developer 3", dvHP: "Phone Number: #3")
developerArray.append(developer3)
let developer4 = Developers(dvName: "Developer 4", dvHP: "Phone Number: #4")
developerArray.append(developer4)
let developer5 = Developers(dvName: "Developer 5", dvHP: "Phone Number: #5")
developerArray.append(developer5)
let developer6 = Developers(dvName: "Developer 6", dvHP: "Phone Number: #6")
developerArray.append(developer6)
myTableView.dataSource = self
myTableView.delegate = self
}
//MARK:- UITableView methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return developerArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "MyCell")
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "MyCell")
}
cell?.textLabel?.text = developerArray[indexPath.row].developerName
cell?.detailTextLabel?.text = developerArray[indexPath.row].developerHP
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detailVC = DetailVC()
detailVC.titleStringViaSegue = self.developerArray[indexPath.row].developerName
self.navigationController?.pushViewController(detailVC, animated: true)
performSegue(withIdentifier: "DevToDetail", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DetailVC {
destination.developer = developerArray[(myTableView.indexPathForSelectedRow?.row)!]
myTableView.deselectRow(at: myTableView.indexPathForSelectedRow!, animated: true)
}
}
}
Use didSelect function of tableView:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destination = storyboard.instantiateViewController(identifier: "<StoryboardID>") as! Destination //StoryboardID of Destination
destination.navigationTitle = developerArray[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
Here is the your DetailVC
class DetailVC: UIViewController {
#IBOutlet weak var productLabel: UILabel!
var titleStringViaSegue: String!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.title = self.titleStringViaSegue
}
}
Change your didselect method like this.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destination = storyboard.instantiateViewController(identifier: "DetailVC") as! DetailVC
destination.titleStringViaSegue = developerArray[indexPath.row].name
self.navigationController?.pushViewController(destination, animated: true)
}
You can give your storyboard ID like this.
create navigationTitle property on destination controller.
class Destination: UIViewController {
var navigationTitle = ""
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = navigationTitle
}
}
check if title available while pushing destination Controller
if segue.destination is DetailVC {
let destination = segue.destination as! DetailVC
if let cell = sender as? UITableViewCell , let title = cell.textLabel?.text {
destination.navigationTitle = title
}
destination.developer = developerArray[(myTableView.indexPathForSelectedRow?.row)!]
myTableView.deselectRow(at: myTableView.indexPathForSelectedRow!, animated: true)
}

How to enlarge tableView on scroll?

I'm sorry if this is a duplicate. I tried to review similar questions in SO - still doesn't quite make me understand how to deal with this.
I have a tableView, three textViews and a UIButton. When the user scrolls the tableView, the tableView should pushes the textFields and the button out the image and take up more space. When that is done I want to continue scrolling through the cells.
(I want one of the textFields to always remain and still show the title.)
I think I need to put the textViews and button above the tableView inside a tableView header after which I need to set certain constraints between the UIView above the tableView and tableView itself. Then I need to play around with the UIScrollViewDelegate and calculate something.
As you guys can probably tell, I'm relatively new in programming and I believe this i why I don't quite understand the related questions. And as you can probably tell too, why I am pretty damn confused about how to solve my problem!
Here's a photo of the VC:
I wan't the tableView to go and cover the 'AddNewPersonBtn' and the two bottom textView - leaving only the top textView, the navigationBar and the tableView on the screen. --> Until you then scroll down again and the rest will be visible again.
And here goes the code for the VC:
import UIKit
import RealmSwift
class AllPersonsInYourDiary: UIViewController, UITableViewDelegate, UITableViewDataSource {
var diary: Diaries?
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var showingDiaryName: UILabel!
#IBOutlet weak var showingDiaryQuestion: UILabel!
#IBOutlet weak var showingExtraIdentifer: UILabel!
#IBOutlet weak var diaryTheme: UIImageView!
#IBOutlet weak var diaryPhoto: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableFooterView = UIView()
self.tableView.tableHeaderView = UIView()
}
override func viewWillAppear(_ animated: Bool) {
tableView.reloadData()
showDiaryIdentifiers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func createNewPersonButton () {
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:
"PersonViewController") as! PersonViewController
controller.mode = .create
controller.diary = diary
self.navigationController?.pushViewController(controller, animated: true)
}
#IBAction func showEditFunc () {
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SettingsVC") as! SettingsVC
controller.diary = diary
self.navigationController?.pushViewController(controller, animated: true)
}
func showDiaryIdentifiers () {
self.showingDiaryName.text = diary?.diaryName
self.showingDiaryQuestion.text = diary?.diaryQuestion
self.showingExtraIdentifer.text = diary?.diaryExtraIdentifier
self.diaryTheme.image = UIImage(data: diary?.diaryTheme ?? Data()) ?? UIImage(named: "Blank")
// self.diaryPhoto.image = UIImage(data: diary?.diaryPhoto ?? Data ()) ?? UIImage(named: "Blank")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return diary!.people.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Person1", for: indexPath) as! PersonCell
let date = DateFormatter.localizedString(from: (diary?.people[indexPath.row].dateCreated)!, dateStyle: .short, timeStyle: .none)
cell.personName.text = diary?.people[indexPath.row].name
cell.personAnswer.text = date
cell.personPhoto.image = UIImage(data: diary?.people[indexPath.row].photo ?? Data()) ?? UIImage(named: "PortaitPhoto")
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:
"PersonViewController") as! PersonViewController
controller.person = diary?.people[indexPath.row]
controller.diary = diary
controller.mode = .show
self.navigationController?.pushViewController(controller, animated: true)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let alert = UIAlertController(title: "Are you sure you wish to delete person?", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "No thanks!", style: .cancel)
let action1 = UIAlertAction(title: "Delete!", style: .destructive, handler: { _ in
let realm = try! Realm()
try! realm.write {
guard let person = self.diary?.people[indexPath.row] else {
return
}
self.diary!.people.remove(at: indexPath.row)
realm.delete(person)
}
tableView.deleteRows(at: [indexPath], with: .fade)
})
alert.addAction(action)
alert.addAction(action1)
present(alert, animated: true)
} }
}

How do You Inherit a Custom TableViewController For An TableView in a ViewController

So I have a custom SwipeCellTableView class that I inherited from when using UITableViewControllers. Now I want to just use that class for an ib outlet table view controller in a regular View Controller. It is proving to be very difficult and seemingly not worth it anymore. Can this be done?
Here is the superclass which inherits from a TableViewController, I have tried to change it to inherit from a view controller but it just doesn't work out
class SwipeTableViewController: UITableViewController, SwipeTableViewCellDelegate {
var cell: UITableViewCell?
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 80.0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SwipeTableViewCell
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
guard orientation == .right else { return nil }
let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
// handle action by updating model with deletion
self.updateModel(at: indexPath)
}
deleteAction.image = UIImage(named: "delete-icon")
return [deleteAction]
}
func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
var options = SwipeTableOptions()
options.expansionStyle = .destructive
//options.transitionStyle = .reveal
return options
}
func updateModel(at indexPath: IndexPath){
//update data model
print("Item deleted from super class")
}
Here is the View Controller I'm trying to access it from:
class GoalsViewController: UIViewController, SwipeTableViewController {
#IBOutlet weak var categoryTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func addCategoryPressed(_ sender: UIButton) {
performSegue(withIdentifier: "showgoalsSeg", sender: self)
}
For reference on how I was using it before when using an actual TableViewController:
class CategoryViewController: SwipeTableViewController {
var categories: Results<Category>? //optional so we can be safe
override func viewDidLoad() {
super.viewDidLoad()
loadCategory()
tableView.rowHeight = 80.0
tableView.separatorStyle = .none
}
//MARK: - Tableview Datasource Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//Only get the count of categories if it's nil, else 1
return categories?.count ?? 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//fetching cell from super view
let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.textLabel?.text = categories?[indexPath.row].name ?? "No Categories Added Yet"
cell.backgroundColor = UIColor(hexString: categories?[indexPath.row].color ?? "000000")
return cell
}
//MARK: - Tableview Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "goToItems", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! ToDoListViewController
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedCategory = categories?[indexPath.row]
}
}
//MARK: - Add New Categories
#IBAction func addButtonPressed(_ sender: Any) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New Category", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Category", style: .default) { (action) in
let newCategory = Category()
newCategory.name = textField.text!
newCategory.color = UIColor.randomFlat.hexValue()
self.save(category: newCategory)
}
alert.addAction(action)
alert.addTextField { (field) in
textField = field
textField.placeholder = "Add a new category"
}
present(alert, animated: true, completion: nil)
}
func save(category: Category){
let realm = try! Realm()
do {
try realm.write{
realm.add(category)
}
} catch {
print("error saving context")
}
tableView.reloadData()
}
override func updateModel(at indexPath: IndexPath) {
super.updateModel(at: indexPath)
let realm = try! Realm()
if let categoryForDeletion = self.categories?[indexPath.row]{
do{
try realm.write{
realm.delete(categoryForDeletion)
}
} catch {
print("error deleting cell")
}
//tableView.reloadData()
}
}
func loadCategory(){
let realm = try! Realm()
categories = realm.objects(Category.self)
tableView.reloadData()
}
Is this even worth persuing? Or doable?

Resources