Swift - 如何检查 TableView 是否为空

7
所以我正在制作这个ToDo-list应用程序。 该应用程序具有本地通知功能,但我只希望在表视图为空时它们才会弹出。简而言之:如何检查表视图是否为空? 这是我的当前代码:
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()
    }

}

有人能帮我吗? 谢谢 ;)


4
你需要检查表格视图是否为空。你需要检查你的数据源中是否有任何数据。 - rmaddy
6个回答

29

在Swift 3中:

if tableView.visibleCells.isEmpty {
    //tableView is empty. You can set a backgroundView for it.
} else {
    //do something
}

1
这个在iOS 13中已经被废弃了。当它们正在被更新的过程中,我们无法检查它们。 - Vinu David Jose

5
您应该检查taskMgr.tasks.count的值。

@Jenoah 别忘了接受最好解决你问题的答案。 - rmaddy

2
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    if taskMgr.tasks.count == 0 {
       //table view is empty here
    }
    return taskMgr.tasks.count    
}

1

..如果TableView为空。

有一个同名的布尔属性,需要在数据源数组上调用。

如果数组不包含任何元素,则为true

taskMgr.tasks.isEmpty

0

如其他答案所述,最好的方法是检查您的数据计数。但如果您想用其他方式进行检查,可以使用:

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;
}

0

由于查询 visibleCellsìndexPathsForVisibleCells 可能不安全,这里我只使用数据源来进行操作。作为对 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)

对于一个 UITableView,它几乎是相同的代码,留给读者作为练习。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接