Swift - when is data actually loaded in TableViewController - swift

I'm very much a Swift beginner - am populating a table view from Firebase data.
In the table footer I want to display some calculated totals under the table columns. However when calling footerCell.configure(priceLines, isPortrait: isPortrait) the priceLines dictionary is still empty.
How to remedy this?
Thanks in advance, André Hartman, Belgium
import UIKit
import FirebaseDatabase
class ListTableViewController: UITableViewController {
var priceLines = [NSDictionary]()
var isPortrait = false
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ListTableViewController.rotated), name: UIDeviceOrientationDidChangeNotification, object: nil)
loadDataFromFirebase()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return priceLines.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("profileCell", forIndexPath: indexPath) as! PriceTableViewCell
cell.configure(priceLines, row: indexPath.row, isPortrait: isPortrait, source: "intraday")
return cell
}
override func tableView(tableView: UITableView,viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! CustomHeaderCell
headerCell.configure(isPortrait)
return headerCell
}
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerCell = tableView.dequeueReusableCellWithIdentifier("FooterCell") as! CustomFooterCell
footerCell.configure(priceLines, isPortrait: isPortrait)
return footerCell
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 30.0
}
override func tableView (tableView:UITableView, heightForHeaderInSection section:Int) -> CGFloat
{
return 50.0;
}
// MARK:- Load data from Firebase
func loadDataFromFirebase() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
refInter.observeEventType(.Value, withBlock: { snapshot in
var tempItems = [NSDictionary]()
for item in snapshot.children {
let child = item as! FIRDataSnapshot
let dict = child.value as! NSDictionary
tempItems.append(dict)
}
self.priceLines = tempItems
self.tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
func rotated()
{
let newDisplay = (UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
if(newDisplay != isPortrait){
self.tableView.reloadData()
}
isPortrait = newDisplay
}
}

The documentation clearly says that
When the table view is about to appear the first time it’s loaded, the
table-view controller reloads the table view’s data.
So, it will reload the table automatically somewhere between viewDidLoad and viewWillAppear. Your priceLines is empty at this point and will be populated with data only when the closure in the method loadDataFromFirebase is fired. I'm not sure when it happens in your case, but as you call implicitly reloadData then you should have already priceLines nonempty (of course if the results in the closure have some data)

Related

Bind UITableView with Combine DataSource

I want to directly link a UITableView with a #Published attribute without using DiffableDataSouce.
If I make the person
struct Person {
let name: String
}
and create the data array:
#Published
var people = [Person(name: "Kim"), Person(name: "Charles")]
So I want to bind my UITableView directly, with something like:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return $people.count()
}
But this gives the error
Cannot convert return expression of type 'Publishers.Count<Published[Person]>.Publisher>' to return type 'Int'
The problem here is that the UITableViewDataSource is pull based (the framework pulls data from your code) but Publishers are push based (they push data to something.) That means that in order to make it work, you need a Mediator (a la the Mediator pattern.)
One option would be to bring in RxSwift/RxCocoa and the RxCombine project to translate between Combine and RxSwift and use the functionality where this already exists. That's a lot for this one ask, but maybe you have other areas where RxCocoa could streamline your code as well.
For just this ask, here is a Mediator that I think would work:
#available(iOS 13.0, *)
final class ViewController: UIViewController {
var tableView: UITableView = UITableView()
#Published var people = [Person(name: "Kim"), Person(name: "Charles")]
var cancellable: AnyCancellable?
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = view.bounds
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
view.addSubview(tableView)
cancellable = $people.sink(receiveValue: tableView.items { tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = item.name
return cell
})
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.people = [Person(name: "Mark"), Person(name: "Allison"), Person(name: "Harold")]
}
}
}
extension UITableView {
func items<Element>(_ builder: #escaping (UITableView, IndexPath, Element) -> UITableViewCell) -> ([Element]) -> Void {
let dataSource = CombineTableViewDataSource(builder: builder)
return { items in
dataSource.pushElements(items, to: self)
}
}
}
class CombineTableViewDataSource<Element>: NSObject, UITableViewDataSource {
let build: (UITableView, IndexPath, Element) -> UITableViewCell
var elements: [Element] = []
init(builder: #escaping (UITableView, IndexPath, Element) -> UITableViewCell) {
build = builder
super.init()
}
func pushElements(_ elements: [Element], to tableView: UITableView) {
tableView.dataSource = self
self.elements = elements
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
elements.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
build(tableView, indexPath, elements[indexPath.row])
}
}

How to delete a cell in the tableview from another View controller?

I am trying to delete a cell in the tableview from another view controller. I have modeled my code similar to the question posted below but I still can't seem to successfully delete the selected row/cell in the CalorieVC when the delete button is pressed in the DeleteVC
Deleting a row of a tableview from another viewcontroller
SideNote: there is button in the cells to popup the DeleteVC, I am also getting an error upon pressing the the deleteBtn in the CalorieVC: DeleteRowInTableviewDelegate on let picked saying Thread 1: Fatal error: Index out of range
import UIKit
class CalorieViewController: UIViewController {
var selectedFood: FoodList! // allows data to be passed into the CalorieVC
var deleteItems: CalorieItem? // passes data to DeleteVC
// allows data to be sepearted into sections
var calorieItems: [CalorieItem] = []
var groupedCalorieItems: [String: [CalorieItem]] = [:]
var dateSectionTitle: [String] = []
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.dataSource = self
tableView.delegate = self
// Allows data in cells to seperate by section
groupedCalorieItems = Dictionary(grouping: calorieItems, by: {$0.foodList.date})
dateSectionTitle = groupedCalorieItems.map{$0.key}.sorted()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DeleteSegue" {
let vc: DeleteViewController = segue.destination as! DeleteViewController
vc.deleteItems = self.deleteItems
// vc.delegate = self
}
}
}
extension CalorieViewController: UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return dateSectionTitle.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let date = dateSectionTitle[section]
return groupedCalorieItems[date]!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let calorieCell = tableView.dequeueReusableCell(withIdentifier: "CalorieCell") as! CalorieCell
let date = dateSectionTitle[indexPath.section]
let caloriesToDisplay = groupedCalorieItems[date]![indexPath.row]
calorieCell.configure(withCalorieItems: caloriesToDisplay.foodList)
return calorieCell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let calorieHeader = tableView.dequeueReusableCell(withIdentifier: "CalorieHeader") as! CalorieHeader
let headerTitle = dateSectionTitle[section]
calorieHeader.dateLbl.text = "Date: \(headerTitle)"
return calorieHeader
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let calorieFooter = tableView.dequeueReusableCell(withIdentifier: "CalorieFooter") as! CalorieFooter
//Cell Total Code
let date = dateSectionTitle[section]
let subtotal = groupedCalorieItems[dispensary]?.map { $0.getCalorieTotal() }.reduce(0, +) ?? 0
calorieFooter.calorieTotal.text = String(subtotal!)
return calorieFooter
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 150
}
}
extension CalorieViewController: DeleteRowInTableviewDelegate {
func deleteRow(inTableview rowToDelete: Int) {
let picked = dateSectionTitle[rowToDelete]
let selectedCell = groupedCalorieItems[dod]
delete(selectedCell)
// calorieItems.remove(at: rowToDelete) // tried using this and I get an error code upon segueing back to the CalorieVC
tableView.reloadData()
}
}
import UIKit
protocol DeleteRowInTableviewDelegate: NSObjectProtocol {
func deleteRow(inTableview rowToDelete: Int)
}
class DeleteViewController: UIViewController {
var modifyItems: CartItem!
var delegate: DeleteRowInTableviewDelegate?
#IBOutlet weak var deleteLbl: UILabel!
#IBOutlet weak var deleteBtn: UIButton!
#IBOutlet weak var cancelBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if isMovingFromParent {
delegate!.deleteRow(inTableview: 1)
}
deleteLbl.text = "Are you sure you want to delete this Food Item from your calorie List?"
}
#IBAction func decline(_ sender: Any) {
dismiss(animated: true)
delegate!.deleteRow(inTableview: 1)
print("Delete Item")
}
#IBAction func cancel(_ sender: Any) {
dismiss(animated: true)
print("Cancel Delete")
}
}
Remove the value from the dataSource
Remove the table cell
extension CalorieViewController: DeleteRowInTableviewDelegate {
func deleteRow(inTableview rowToDelete: Int) {
if caloriesItems.count > rowToDelete {
calorieItems.remove(at: rowToDelete)
tableView.deleteRows(at: [IndexPath(row: rowToDelete, section: 0)], with: .automatic)
} else {
print("index not present")
}
}
}
Do not call reloadData just to delete one row. This is a bad practice.
Use deleteRows instead.

tableView doesn't show data in swift

I'm trying to create a tableView within a viewController. I know it is annoying, but the table looks much better that way. I am also trying to incorporate data from Firebase to put into the table. Unfortunately when I run the code, it only shows a blank table. The console was able to print the desired data, but it just won't show on the actual table. Please let me know what I'm doing wrong. Many thanks!
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var user = Auth.auth().currentUser
var users = [Users]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.reloadData()
fetchUser()
}
func fetchUser() {
Database.database().reference(fromURL: "https://yala-2018.firebaseio.com/").child("users").observe(.childAdded, with: { (DataSnapshot) in
if let dictionary = DataSnapshot.value as? [String: AnyObject] {
let user = Users()
// user.setValuesForKeys(dictionary)
user.name = dictionary["name"] as! String
user.age = dictionary["age"] as! String
user.sex = dictionary["sex"] as! String
self.users.append(user)
print(user.name, user.age)
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
})
}
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "guide", for: indexPath)
let user = users[indexPath.row]
cell.textLabel?.text = user.name
cell.detailTextLabel?.text = "Age: \(user.age) Sex: \(user.sex)"
// Configure the cell...
return cell
}
func tableView(tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
Change this to 1 as by 0 you mean no sections which will display empty tableView even if there is a data , or remove it as by default it's 1
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

I get the error "index 6 beyond bounds [0 .. 5]' " when implementing search in my app

Here's my code. While following multiple tutorials on how to implement search in Swift I've had no luck.
import UIKit
class DataTableExercisesTableViewController: UITableViewController, UISearchBarDelegate, UISearchResultsUpdating {
var exercises = ["Abs", "Arms", "Back", "Chest", "Legs", "Shoulders", "Triceps"]
var searchActive : Bool = false
#IBOutlet weak var searchBar: UISearchBar!
var filteredTableData = [String]()
var resultSearchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
// Reload the table
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return exercises.count;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell;
if (self.resultSearchController.active) {
cell.textLabel?.text = filteredTableData[indexPath.row]
return cell
}
else {
cell.textLabel?.text = exercises[indexPath.row]
return cell
}
}
func updateSearchResultsForSearchController(searchController: UISearchController)
{
filteredTableData.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %#", searchController.searchBar.text!)
let array = (exercises as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
self.tableView.reloadData()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
I've been having trouble implementing search from different tutorials and just doesn't seem to be working out too well. Any insight is much appreciated.
Your numberOfRowsInSection is always returning exercises.count. But when you are filtering, you are not using exercises, but a smaller array, filteredTableData. So, just as in cellForRowAtIndexPath, you need to change your answer if you are filtering.
The best solution is before access the array value just the check the total count should less the the index you want fetch from the array or use below way to iterate the array
EX :
let arrayOfInts: [Int] = [1, 2, 3];
for i in arrayOfInts {
print(i);
}
In your case you could change the code :
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowCount = 0
if(self.resultSearchController.active){
rowCount = filteredTableData.count
}
else{
rowCount = exercises.count
}
return rowCount;
}

Saving values to UserDefults from Textfield in TableView : Swift

I am trying to save values from a tableview that users will input into the textfield, the problem is that I do not know how to access the new value and replace the string in the array.
So basically the app will display fields based on what the user wants and then the user can edit those values to their liking. Once the textfields have been updated, the values are stored again in userdefaults so that the next time the tableview is opened, the update values will appear.
This is what the tableviewcontroller looks like at the moment:
//
// Asset1TableViewController.swift
// Net Calc 2
//
// Created by Joshua Peterson on 30/06/2015.
// Copyright © 2015 Peterson Productions. All rights reserved.
//
import UIKit
class Asset1TableViewController: UITableViewController {
var dataHolder: [NSString] = [NSString]()
var finalDataHolder: [NSString] = [NSString]()
var acountAmountHolder: [NSString] = [NSString]()
var finalAccountAmountHolder: [NSString] = [NSString]()
let defaults = NSUserDefaults.standardUserDefaults()
let key1 = "keySave1"
let key2 = "keySave2"
override func viewDidLoad() {
super.viewDidLoad()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let storedTitleValue : NSArray? = self.defaults.arrayForKey(self.key1) {
if storedTitleValue == nil {
self.dataHolder = [NSString]()
} else {
let readArray : [NSString] = storedTitleValue as! [NSString]
for element in readArray {
self.dataHolder.append(element as String)
self.finalDataHolder.append(element as String)
}
}
}
if let storedAmountValue : NSArray? = self.defaults.arrayForKey(self.key2) {
if storedAmountValue == nil {
self.acountAmountHolder = [NSString]()
} else {
let readArray : [NSString] = storedAmountValue as! [NSString]
for element in readArray {
self.acountAmountHolder.append(element as String)
self.finalAccountAmountHolder.append(element as String)
}
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataHolder.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Account1Cell", forIndexPath: indexPath) as! Account1Cell
cell.AccountLabel.text = dataHolder[indexPath.row] as String
cell.AccountAmount.text = acountAmountHolder[indexPath.row] as String
return cell
}
#IBAction func addButtonTapped(sender: AnyObject) {
let newAccounTitle = "Account Name"
let newAccountAmount = "R0.00"
dataHolder.append(newAccounTitle)
acountAmountHolder.append(newAccountAmount)
tableView.reloadData()
}
#IBAction func saveButtonTapped(sender: AnyObject) {
// Save
defaults.setObject(dataHolder as Array, forKey: key1)
defaults.setObject(acountAmountHolder as Array, forKey: key2)
defaults.synchronize()
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
dataHolder.removeAtIndex(indexPath.row)
acountAmountHolder.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
}
I have tried to apply some of the code that i have found on the website but the problem is that I cant actually connect to the cell.
Ok so after some research I have added a few functions to the custom cell class so that it looks like this:
import UIKit
protocol TableViewCellDelegate {
// Indicates that the edit process has begun for the given cell
func cellDidBeginEditing(editingCell: Account1Cell)
// Indicates that the edit process has committed for the given cell
func cellDidEndEditing(editingCell: Account1Cell)
}
class Account1Cell: UITableViewCell, UITextFieldDelegate {
#IBOutlet weak var AccountLabel: UITextField!
#IBOutlet weak var AccountAmount: UITextField!
var delegate: TableViewCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
AccountLabel.delegate = self
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
// close the keyboard on Enter
AccountLabel.resignFirstResponder()
return false
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
// disable editing of completed to-do items
return true
}
func textFieldDidEndEditing(textField: UITextField) {
if AccountLabel != nil {
let newAccountLabel = AccountLabel.text
print(newAccountLabel) // Prints out the new edited text!!!!!!!!
}
if delegate != nil {
delegate!.cellDidEndEditing(self)
}
}
func textFieldDidBeginEditing(textField: UITextField) {
if delegate != nil {
delegate!.cellDidBeginEditing(self)
}
}
}
Now what I need to do is either replace that value in the Array at the index (which i think is going to be rather complicated) or create some sort of loop that will read ALL the values and simply store all of the new values to UserDefaults. Maybe there is something else?
Any help is appreciated!!
You should have a protocol in your custom cell like this, and call it when the text field in the cell gets modified:
protocol TableViewCellToTVController{
func cellCurrentlyEditing(editingCell: Account1Cell) -> Int
}
....
func textFieldShouldReturn(textField: UITextField) -> Bool {
// close the keyboard on Enter
let myrow: Int? = self.delegate_special?.cellCurrentlyEditing(self)
println("cellCurrentlyEditing got called from delegate" , myrow)
AccountLabel.resignFirstResponder()
return false
}
implement this function in tableviewcontroller to know which row got selected :
func cellCurrentlyEditing(editingCell: Account1Cell) -> Int{
var rowNum = 0
let indexP: NSIndexPath = tableView.indexPathForCell(editingCell)!
rowNum = indexP.row
return rowNum
}
also make your tableviewcontroller the delegate for each cell:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Account1Cell", forIndexPath: indexPath) as! Account1Cell
cell.AccountLabel.text = dataHolder[indexPath.row] as String
cell.AccountAmount.text = acountAmountHolder[indexPath.row] as String
cell.delegate_special = self;
return cell
}