DZNEmptyDataSet

Episode #184 | 9 minutes | published on 08/27/2015
Subscribers Only
In this episode we take a look a DZNEmptyDataSet, a useful library for providing a more inviting UI when you have no content to display inside of a table view or collection view. We'll also see how to leverage NSAttributedString to provide styling of the text that is displayed on the screen.

Episode Links

Installing with CocoaPods

In your Podfile, add:

use_frameworks! # if using Swift

pod 'DZNEmptyDataSet'

Then run pod install.

Setting Your Table View

import DZNEmptyDataSet

class ViewController: UITableViewController, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.emptyDataSetSource = self
        self.tableView.emptyDataSetDelegate = self
    }

    ...
}

We can hide the fake table view rows we get when using a Plain-style table view that has no rows by adding a blank footer. This causes the fake rows to not appear, and the footer has a height of 0, so it effectively removes the effect.

self.tableView.tableFooterView = UIView()

Configuring the empty view


    func imageForEmptyDataSet(scrollView: UIScrollView!) -> UIImage! {
        return UIImage(named: "empty-book")
    }

    func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
        let text = "You have no items"
        let attribs = [
            NSFontAttributeName: UIFont.boldSystemFontOfSize(18),
            NSForegroundColorAttributeName: UIColor.darkGrayColor()
        ]

        return NSAttributedString(string: text, attributes: attribs)
    }

    func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
        let text = "Add items to track the things that are important to you. Add your first item by tapping the + button."

        var para = NSMutableParagraphStyle()
        para.lineBreakMode = NSLineBreakMode.ByWordWrapping
        para.alignment = NSTextAlignment.Center

        let attribs = [
            NSFontAttributeName: UIFont.systemFontOfSize(14),
            NSForegroundColorAttributeName: UIColor.lightGrayColor(),
            NSParagraphStyleAttributeName: para
        ]

        return NSAttributedString(string: text, attributes: attribs)
    }

    func buttonTitleForEmptyDataSet(scrollView: UIScrollView!, forState state: UIControlState) -> NSAttributedString! {
        let text = "Add First Item"
        let attribs = [
            NSFontAttributeName: UIFont.boldSystemFontOfSize(16),
            NSForegroundColorAttributeName: view.tintColor
        ]

        return NSAttributedString(string: text, attributes: attribs)
    }

Handling the button tap

    func emptyDataSetDidTapButton(scrollView: UIScrollView!) {
        println("Tapped")
    }
blog comments powered by Disqus