[swift] DZNEmptyDataSet을 사용하여 커스텀 디자인된 배경 이미지 추가하기

DZNEmptyDataSet은 UITableView나 UICollectionView와 같은 빈 상태의 데이터셋을 표시할 수 있는 라이브러리입니다. 이를 사용하여 커스텀 디자인된 배경 이미지를 추가하는 방법을 알아보겠습니다.

1. DZNEmptyDataSet 라이브러리 추가하기

먼저, 프로젝트에 DZNEmptyDataSet 라이브러리를 추가해야 합니다. 이를 위해서는 Cocoapods를 사용하여 라이브러리를 설치해야 합니다. Podfile에 다음과 같이 라이브러리를 추가합니다:

pod 'DZNEmptyDataSet'

그리고 터미널에서 다음 명령어를 실행하여 라이브러리를 설치합니다:

$ pod install

2. DZNEmptyDataSetDelegate 및 DZNEmptyDataSetSource 설정하기

DZNEmptyDataSet을 사용하기 위해서는 DZNEmptyDataSetDelegateDZNEmptyDataSetSource의 메소드들을 구현해야 합니다. 이를 위해 다음과 같이 UITableViewDelegateUITableViewDataSource 프로토콜을 채택한 후, DZNEmptyDataSetDelegateDZNEmptyDataSetSource 프로토콜을 추가합니다:

class YourViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource {
    // your code here
}

3. 배경 이미지 추가하기

다음으로, DZNEmptyDataSet을 사용하여 커스텀 디자인된 배경 이미지를 추가하는 방법은 아래와 같습니다:

func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
    return UIImage(named: "empty_data_background_image")
}

이 메소드에서는 반환값으로 표시할 배경 이미지를 지정해야 합니다. 위 예제에서는 “empty_data_background_image”라는 이름의 이미지 파일을 사용하고 있습니다. 해당 이미지 파일은 프로젝트 내에 존재해야 합니다.

위의 image(forEmptyDataSet:) 메소드가 호출되면, 해당 이미지가 빈 상태의 데이터셋 배경에 표시됩니다.

4. 전체 코드 예제

import UIKit
import DZNEmptyDataSet

class YourViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource {

    @IBOutlet weak var tableView: UITableView!
    // other properties and methods

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        tableView.emptyDataSetDelegate = self
        tableView.emptyDataSetSource = self
    }

    // MARK: - UITableViewDelegate, UITableViewDataSource methods

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // return number of rows in section
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // configure and return table view cell at index path
    }

    // MARK: - DZNEmptyDataSetDelegate, DZNEmptyDataSetSource methods

    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        return UIImage(named: "empty_data_background_image")
    }

    func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        // return title for empty dataset
    }

    func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        // return description for empty dataset
    }

    // other DZNEmptyDataSetDelegate, DZNEmptyDataSetSource methods
}

위의 예제 코드에서는 UITableViewDelegateUITableViewDataSource의 대부분의 메소드와 DZNEmptyDataSetDelegateDZNEmptyDataSetSource의 메소드 구현은 생략되어 있습니다. 필요에 따라 해당 메소드들을 추가로 구현하여 사용하면 됩니다.

5. 참고 자료