[swift] DZNEmptyDataSet을 통해 빈 상태의 뷰를 만드는 방법

앱에서 데이터가 없는 경우 또는 네트워크 문제로 인해 데이터를 가져올 수 없는 경우에는 사용자에게 빈 상태를 보여주는 것이 중요합니다. 이때 DZNEmptyDataSet은 UITableView와 UICollectionView를 사용하여 빈 상태의 뷰를 생성하는 자주 사용되는 라이브러리입니다. 이번 포스트에서는 DZNEmptyDataSet을 사용하여 빈 상태의 뷰를 만드는 방법에 대해 알아보겠습니다.

1. DZNEmptyDataSet 라이브러리 설치

DZNEmptyDataSet은 CocoaPods를 통해 설치할 수 있습니다. Podfile에 다음과 같이 추가해주세요.

pod 'DZNEmptyDataSet'

그리고 터미널에서 다음 명령을 실행하여 라이브러리를 설치해주세요.

pod install

2. DZNEmptyDataSet 사용하기

2.1. 델리게이트 설정하기

DZNEmptyDataSet을 사용하기 위해서는 UITableViewDelegate 또는 UICollectionViewDelegate를 구현하는 클래스에서 DZNEmptyDataSetSource와 DZNEmptyDataSetDelegate 프로토콜을 추가해주어야 합니다.

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

    // TableView를 위한 DZNEmptyDataSetSource 메서드 구현

    func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18.0),
                          NSAttributedString.Key.foregroundColor: UIColor.black]
        return NSAttributedString(string: "빈 상태", attributes: attributes)
    }
    
    func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14.0),
                          NSAttributedString.Key.foregroundColor: UIColor.gray]
        return NSAttributedString(string: "데이터가 없습니다.", attributes: attributes)
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        return UIImage(named: "emptyStateImage")
    }

    // TableView를 위한 DZNEmptyDataSetDelegate 메서드 구현

    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
        // 빈 상태 뷰를 표시할지 여부를 결정하는 메서드
        return true
    }
    
    func emptyDataSetWillAppear(_ scrollView: UIScrollView) {
        // 빈 상태 뷰가 나타날 때 호출되는 메서드
    }
    
    func emptyDataSetDidAppear(_ scrollView: UIScrollView) {
        // 빈 상태 뷰가 나타난 후 호출되는 메서드
    }
}

2.2. 빈 상태의 뷰 디자인하기

TableView나 CollectionView의 빈 상태를 나타내는 뷰의 디자인을 변경하려면 DZNEmptyDataSet의 속성을 설정할 수 있습니다. 위의 코드에서 사용된 메서드들은 빈 상태 뷰의 제목, 설명, 이미지를 설정하기 위한 것입니다. 원하는 디자인에 맞게 속성을 설정해주세요.

3. 추가 설정

DZNEmptyDataSet을 사용하기 위해 기본 설정 외에도 몇 가지 추가적인 설정이 필요할 수 있습니다. 예를 들어, TableView의 데이터가 업데이트되었을 때 빈 상태 뷰를 재로딩하려면 다음과 같은 코드를 추가해주세요.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    tableView.reloadEmptyDataSet()
}

마무리

DZNEmptyDataSet은 빈 상태의 뷰를 만들기 위한 강력한 라이브러리입니다. 위의 단계를 따라가면 앱에서 데이터가 없는 경우에 훌륭한 사용자 경험을 제공할 수 있습니다. 자세한 내용은 공식 GitHub 저장소에서 확인할 수 있습니다.

샘플 코드의 몇 가지 세부 사항은 생략되었으므로, 위의 코드를 기반으로 자신의 앱에 맞게 수정해주시기 바랍니다.