[swift] DZNEmptyDataSet을 사용하여 빈 상태뷰에 텍스트 나열하기

앱 개발 중에는 데이터가 없을 때 빈 상태를 보여주는 뷰가 필요할 수 있습니다. 이때 DZNEmptyDataSet 라이브러리를 사용하면 쉽게 빈 상태뷰를 만들 수 있습니다. DZNEmptyDataSet은 UITableView, UICollectionView, UIScrollView와 같은 클래스에서 사용할 수 있습니다.

DZNEmptyDataSet 라이브러리 설치하기

먼저 CocoaPods를 사용하여 DZNEmptyDataSet 라이브러리를 설치해야 합니다. Podfile에 다음과 같이 라이브러리를 추가하세요.

pod 'DZNEmptyDataSet'

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

pod install

DZNEmptyDataSet 사용하기

DZNEmptyDataSet을 사용하려면 해당 뷰 클래스에서 DZNEmptyDataSetSource와 DZNEmptyDataSetDelegate 프로토콜을 구현해야 합니다. 뷰 컨트롤러 클래스를 다음과 같이 업데이트하세요.

import UIKit
import DZNEmptyDataSet

class ViewController: UIViewController {
  
  @IBOutlet weak var tableView: UITableView!
  
  override func viewDidLoad() {
    super.viewDidLoad()
    tableView.emptyDataSetSource = self
    tableView.emptyDataSetDelegate = self
  }
  
}

extension ViewController: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  
  func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
    let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)]
    return NSAttributedString(string: "데이터가 없습니다.", attributes: attributes)
  }
  
  func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
    let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)]
    return NSAttributedString(string: "데이터를 추가해주세요.", attributes: attributes)
  }
  
}

위 코드에서는 UITableView를 사용하는 예시로 작성하였습니다. 빈 상태일 때 보여줄 제목과 설명을 설정하기 위해 title(forEmptyDataSet:)description(forEmptyDataSet:) 메서드를 구현하였습니다. 각각의 메서드에서는 NSAttributedString으로 제목과 설명을 설정하고 폰트를 지정할 수 있습니다.

추가적으로 더 많은 설정 옵션을 사용하고 싶다면 DZNEmptyDataSetDelegate와 DZNEmptyDataSetSource 프로토콜을 참조하세요.

마무리

DZNEmptyDataSet은 빈 상태일 때 사용자에게 이해하기 쉬운 메시지를 전달할 수 있는 유용한 라이브러리입니다. 다양한 기능과 옵션을 제공하므로, 앱의 사용자 경험 향상을 위해 적극적으로 활용해보세요.

참고 자료