[swift] DZNEmptyDataSet을 사용하여 빈 상태뷰에 추가적인 메시지 추가하기

앱 개발 중에는 데이터가 없을 때에도 사용자들에게 적절한 메시지를 전달하기 위해 빈 상태 뷰를 추가해야 할 때가 있습니다. 이를 위해 DZNEmptyDataSet 라이브러리를 사용하면 간단하게 빈 상태 뷰에 추가적인 메시지를 적용할 수 있습니다.

DZNEmptyDataSet 이란?

DZNEmptyDataSet은 UITableView 및 UICollectionView 등에서 데이터가 없을 때 빈 상태 뷰를 쉽게 추가할 수 있는 라이브러리입니다. 이를 사용하여 사용자에게 적절한 메시지를 표시할 수 있습니다.

설치

CocoaPods를 통해 DZNEmptyDataSet을 설치합니다. Podfile에 아래와 같이 추가하고 pod install을 실행합니다.

pod 'DZNEmptyDataSet'

사용 방법

  1. UITableViewDelegate 또는 UICollectionViewDelegate 프로토콜을 채택합니다.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    // ...
}
  1. UITableViewDelegate 또는 UICollectionViewDelegateemptyDataSetSourceemptyDataSetDelegate 속성을 구현합니다.
tableView.emptyDataSetSource = self
tableView.emptyDataSetDelegate = self
  1. emptyDataSetTitle, emptyDataSetDescription, emptyDataSetImage(선택사항) 등을 통해 원하는 메시지를 설정합니다.
extension ViewController: DZNEmptyDataSetSource {
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let attributes: [NSAttributedString.Key : Any] = [
            .font: UIFont.boldSystemFont(ofSize: 18.0),
            .foregroundColor: UIColor.gray
        ]
        return NSAttributedString(string: "데이터가 없습니다.", attributes: attributes)
    }

    func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let attributes: [NSAttributedString.Key : Any] = [
            .font: UIFont.systemFont(ofSize: 14.0),
            .foregroundColor: UIColor.lightGray
        ]
        return NSAttributedString(string: "데이터를 추가해주세요.", attributes: attributes)
    }

    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        return UIImage(named: "empty_state_image")
    }
}
  1. 메시지의 위치나 옵션을 추가로 설정하고 싶다면, emptyDataSetWillAppear, emptyDataSetWillDisappear 등의 델리게이트 메서드를 사용합니다.
extension ViewController: DZNEmptyDataSetDelegate {
    func emptyDataSetWillAppear(_ scrollView: UIScrollView!) {
        // 빈 상태 뷰가 화면에 나타날 때의 동작을 설정
    }

    func emptyDataSetWillDisappear(_ scrollView: UIScrollView!) {
        // 빈 상태 뷰가 화면에서 사라질 때의 동작을 설정
    }
}

마무리

위의 방법을 통해 DZNEmptyDataSet을 사용하여 빈 상태 뷰에 추가적인 메시지를 보여줄 수 있습니다. 이를 활용하여 사용자에게 적절한 안내 메시지를 전달하고 앱의 사용성을 향상시킬 수 있습니다.