[swift] DZNEmptyDataSet을 사용하여 빈 상태뷰에 커스텀 디자인된 테이블 셀 추가하기

DZNEmptyDataSet은 iOS 앱에서 빈 상태를 나타내는 뷰를 간단하게 구현할 수 있는 라이브러리입니다. 이 라이브러리를 사용하면 테이블 뷰에 데이터가 없을 때 커스텀 디자인된 빈 상태뷰를 쉽게 추가할 수 있습니다.

설치하기

DZNEmptyDataSet은 CocoaPods를 통해 설치할 수 있습니다. Podfile에 다음과 같이 추가하고 pod install 명령어를 실행하세요.

pod 'DZNEmptyDataSet'

사용방법

  1. UITableViewDelegate를 구현한 뷰 컨트롤러에서 DZNEmptyDataSetSourceDZNEmptyDataSetDelegate 프로토콜을 채용합니다.
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
    //...
}
  1. 테이블 뷰의 emptyDataSetSourceemptyDataSetDelegate를 설정합니다.
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.emptyDataSetSource = self
        tableView.emptyDataSetDelegate = self
    }
    
    //...
}
  1. DZNEmptyDataSetSource 프로토콜의 title(forEmptyDataSet:) 메서드를 구현하여 빈 상태뷰의 타이틀을 설정합니다.
func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
    let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16.0),
                      NSAttributedString.Key.foregroundColor: UIColor.gray]
    return NSAttributedString(string: "데이터가 없습니다.", attributes: attributes)
}
  1. DZNEmptyDataSetSource 프로토콜의 image(forEmptyDataSet:) 메서드를 구현하여 빈 상태뷰의 이미지를 설정합니다.
func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
    return UIImage(named: "empty-state-image")
}
  1. DZNEmptyDataSetSource 프로토콜의 buttonImage(for:state:) 메서드를 구현하여 빈 상태뷰에 버튼 이미지를 설정합니다.
func buttonImage(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> UIImage? {
    return UIImage(named: "button-image")
}
  1. DZNEmptyDataSetDelegate 프로토콜의 emptyDataSet(_ scrollView: UIScrollView, didTapButton: UIButton) 메서드를 구현하여 버튼을 클릭했을 때의 동작을 설정합니다.
func emptyDataSet(_ scrollView: UIScrollView, didTapButton button: UIButton) {
    // 버튼을 클릭했을 때 수행할 동작 구현
}
  1. 테이블 뷰의 reloadData() 메서드를 호출하여 빈 상태뷰를 업데이트합니다.
tableView.reloadData()

참고자료