Swift - How to check if TableView is empty
Asked Answered
U

6

7

So i'm making this ToDo-list app. This app has local notifications, but i only want them to pop-up if the tableview is empty. To keep it short : How do i check if the tableview is empty?

This is my current code :

import UIKit

class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


@IBOutlet var tblTasks : UITableView!
@IBOutlet weak var countLbl: UILabel!
 var localNotification = UILocalNotification()

//For persisting data
let defaults = NSUserDefaults.standardUserDefaults()

override func viewDidLoad() {
    super.viewDidLoad()
    self.tblTasks.reloadData()


    // localNotification.alertAction = "Je hebt nog taken die gedaan moeten worden!"
    localNotification.alertBody = "Je hebt nog taken die gedaan moeten worden! Namelijk nog \(updateCount)"
    localNotification.timeZone = NSTimeZone.localTimeZone()

    localNotification.fireDate = NSDate(timeIntervalSinceNow: 10)
    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

}

override func viewWillAppear(animated: Bool) {
    self.tblTasks.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return taskMgr.tasks.count

}

//Define how our cells look - 2 lines a heading and a subtitle
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Default Tasks")

    //Assign the contents of our var "items" to the textLabel of each cell
    cell.textLabel!.text = taskMgr.tasks[indexPath.row].name
    cell.detailTextLabel!.text = taskMgr.tasks[indexPath.row].description
    cell.backgroundColor = UIColor.clearColor()

    return cell

}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){

    if (editingStyle == UITableViewCellEditingStyle.Delete){

        taskMgr.removeTask(indexPath.row)
        tblTasks.reloadData()
    }

}

Anyone who can help me? Thanks ;)

Uncap answered 27/4, 2016 at 15:32 Comment(1)
You don't check if the table view is empty. You check to see if your data source has any data in it.Tanatanach
C
29

In Swift 3:

if tableView.visibleCells.isEmpty {
    //tableView is empty. You can set a backgroundView for it.
} else {
    //do something
}
Cloud answered 10/9, 2017 at 20:18 Comment(1)
This one is deprecated in iOS 13. we cant check this while they were in the process of being updatedTut
A
5

You should check taskMgr.tasks.count value.

Anorak answered 27/4, 2016 at 15:34 Comment(1)
@Jenoah Don't forget to accept the answer that best solved your issue.Tanatanach
J
2
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    if taskMgr.tasks.count == 0 {
       //table view is empty here
    }
    return taskMgr.tasks.count    
}
Judaica answered 27/4, 2016 at 15:38 Comment(0)
L
1

.. if TableView is empty.

There is a boolean property with the same name , to be called on the data source array.

It's true if the array contains no elements.

taskMgr.tasks.isEmpty
Lobe answered 27/4, 2016 at 15:39 Comment(0)
D
0

As mentioned in other answers, best way is to check with count of your data. But if you want to check with any other way, you can use:

if tableView.visibleCells.count == 0 {
      // tableView is empty. You can set a backgroundView for it.
      let label = UILabel(frame: CGRectMake(0, 0, tableView.bounds.size.width, tableView.bounds.size.height))
      label.text = "No Data"
      label.textColor = UIColor.blackColor();
      label.TextAlignment = .Center
      label.sizeToFit()
      tableView.backgroundView = label;
      tableView.separatorStyle = .None;
}
Designation answered 22/6, 2016 at 9:4 Comment(0)
M
0

As it might be unsafe to query visibleCells and also ìndexPathsForVisibleCells, here's my take using solely the datasource. As an extension on UICollectionView:

import UIKit.UICollectionView

public extension UICollectionView {

    /// Returns true, if there are no items. False, otherwise.
    @inlinable var CC_isEmpty: Bool {
        guard let dataSource = self.dataSource else { return true }
        // Ideally we'd just inspect the visibleCells, but if we're checking in the false moment,
        // UICollectionView will complain about us checking while updating, so we better directly
        // refer to the data source. Unfortunately, `UICollectionView` does not have an API for `isEmpty()`.
        guard let numberOfSections = dataSource.numberOfSections?(in: self), numberOfSections > 0 else { return true }
        for section in 0..<numberOfSections {
            let entriesPerSection = dataSource.collectionView(self, numberOfItemsInSection: section)
            if entriesPerSection > 0 {
                return false
            }
        }
        return true
    }

}
UICollectionView+Emptyness.swift (END)

For a UITableView, it's almost the same code and left as an exercise to the reader.

Monophony answered 2/12, 2020 at 8:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.