LoginSignup
29
11

More than 5 years have passed since last update.

【swift】tableViewに何もなければ、吉岡里帆ちゃんが出現する

Last updated at Posted at 2017-10-04

【swift】tableViewに何もなければ、吉岡里帆ちゃんが出現する

  • 今回は、UITabaleViewやUICollectionViewに表示する要素が0であれば、吉岡里帆さん が出現するようにします。
  • アプリ作りのときに毎回お世話になっているライブラリで dzenbot/DZNEmptyDataSet という、UITabaleViewやUICollectionViewに表示する要素が何もなければ任意の画像や文字を設定してくれます。

完成形はこんな感じです(要素が0のとき)

Simulator Screen Shot - iPhone 8 Plus - 2017-10-04 at 22.39.52.png

要素があれば普通にインデックスを表示します

Simulator Screen Shot - iPhone 8 Plus - 2017-10-04 at 22.41.58.png

実装してみる

cocoapodかcarthageでdzenbot/DZNEmptyDataSetを入れる

cocoapod

  pod 'DZNEmptyDataSet'
$ pod install

carthage

github "dzenbot/DZNEmptyDataSet"
$ carthage update --platform iOS

ソースコードはこれだけ

  • 画像はriho1Assets.xcassets に入れてあります。
  • numberOfRowsInSectionを0にすると吉岡里帆ちゃんが出現するはずです。
  • ポイントとして今回delegateの設定は、Storyboardだけで行います。
viewController.swift
import UIKit
import DZNEmptyDataSet

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "\(indexPath.row)"
        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10 // <= ここを0にしたときに、吉岡里帆ちゃんが出現すれば成功
    }
}

extension ViewController: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        return UIImage(named: "riho1")
    }
}

Storyboardの設定

UITableViewとDZNEmptyDataSetのdelegateをStoryboardで設定する <- ポイント!!

  • referencing Outlets に

    • UITableViewDataSource
    • UITableViewDelagate
    • DZNEmptyDataSetSource
    • DZNEmptyDataSetDelegate が設定されています。
  • このとき、viewControllerにDZNEmptyDataSet がimportされていることと、StoryboardにviewControllerがcustom classに設定されていれば、設定できます。

  • 下図のように、tableViewをControllを押しながらViewControllerのところで離すと、delegateの設定ができます。ソースコードの中でいちいち ????.delegate = self としなくて良くなります。

Screen Shot 2017-10-04 at 22.53.48.png


Screen Shot 2017-10-04 at 22.36.56.png

完成形はこちら

yosidariho_full.gif

まとめ

  • DZNEmptyDataSetを使えば、tableViewやcolelctionView scrollViewに何もないときに画像やテキストをかんたんに表示することができます。
  • おすすめです!
29
11
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
11