[swift] DZNEmptyDataSet을 사용하여 테이블 뷰에서 빈 상태 메시지 표시하기

테이블 뷰를 사용하다보면 데이터가 없는 경우에 빈 상태의 메시지를 표시해야 할 때가 있습니다. 이때 DZNEmptyDataSet 라이브러리를 사용하면 간단하게 해결할 수 있습니다. DZNEmptyDataSet은 테이블 뷰가 비어있을 때 빈 상태 메시지, 이미지, 버튼 등을 커스터마이즈하여 표시할 수 있는 라이브러리입니다.

이번 글에서는 DZNEmptyDataSet을 사용하여 테이블 뷰에서 빈 상태 메시지를 표시하는 방법에 대해 알아보겠습니다.

DZNEmptyDataSet 설치하기

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

pod 'DZNEmptyDataSet'

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

$ pod install

DZNEmptyDataSet 적용하기

DZNEmptyDataSet을 사용하기 위해서는 아래와 같은 단계를 따라야 합니다.

  1. UITableViewDelegate, UITableViewDataSource를 상속받는 클래스에 DZNEmptyDataSetSourceDZNEmptyDataSetDelegate 프로토콜을 추가해주세요.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
    // ...
}
  1. DZNEmptyDataSetSource 프로토콜을 구현하여 빈 상태일 때 표시할 내용을 커스터마이즈해주세요.
func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
    let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18.0),
                      NSAttributedString.Key.foregroundColor: UIColor.darkGray]
    return NSAttributedString(string: "데이터가 없습니다.", attributes: attributes)
}

func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
    let paragraph = NSMutableParagraphStyle()
    paragraph.lineBreakMode = .byWordWrapping
    paragraph.alignment = .center

    let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14.0),
                      NSAttributedString.Key.foregroundColor: UIColor.lightGray,
                      NSAttributedString.Key.paragraphStyle: paragraph]
    return NSAttributedString(string: "데이터를 불러오고 있지 않습니다.", attributes: attributes)
}

func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> NSAttributedString? {
    let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16.0),
                      NSAttributedString.Key.foregroundColor: UIColor.blue]
    return NSAttributedString(string: "다시 시도", attributes: attributes)
}

func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
    return UIImage(named: "empty_state_image")
}
  1. DZNEmptyDataSetDelegate 프로토콜을 구현하여 빈 상태일 때 발생하는 이벤트를 처리해주세요.
func emptyDataSet(_ scrollView: UIScrollView, didTapButton button: UIButton) {
    // 다시 시도 버튼을 눌렀을 때 처리할 내용을 작성해주세요.
    // 예: 데이터를 다시 불러오기 위해 API 호출
}
  1. tableView.emptyDataSetSourcetableView.emptyDataSetDelegate 프로퍼티를 사용하여 테이블 뷰에 DZNEmptyDataSet을 적용해주세요.
override func viewDidLoad() {
    super.viewDidLoad()

    tableView.emptyDataSetSource = self
    tableView.emptyDataSetDelegate = self
}

이제 위의 단계를 모두 수행하면, 테이블 뷰가 비어있을 때 미리 설정한 빈 상태의 메시지, 이미지, 버튼 등이 표시됩니다.

결론

DZNEmptyDataSet 라이브러리를 사용하면 테이블 뷰에서 빈 상태 메시지를 간단하게 표시할 수 있습니다. 필요한 경우 라이브러리의 다양한 커스터마이즈 옵션을 활용하여 더 다양한 빈 상태를 표현할 수도 있습니다.

이상으로 DZNEmptyDataSet을 사용하여 테이블 뷰에서 빈 상태 메시지를 표시하는 방법에 대해 알아보았습니다.