[swift] DZNEmptyDataSet을 사용하여 빈 상태뷰의 버튼 스타일 변경하기

앱을 개발하다 보면 데이터가 없는 상태에서 빈 상태뷰를 보여주는 경우가 있습니다. 이 때 DZNEmptyDataSet 라이브러리를 사용하면 편리하게 빈 상태뷰를 커스터마이징할 수 있습니다. 이번 포스트에서는 DZNEmptyDataSet을 사용하여 빈 상태뷰에 있는 버튼의 스타일을 변경하는 방법을 알아보겠습니다.

1. DZNEmptyDataSet 라이브러리 설치하기

먼저, DZNEmptyDataSet 라이브러리를 설치해야 합니다. Cocoapods를 사용한다면 Podfile에 다음과 같이 추가하고, pod install 명령어를 실행합니다.

pod 'DZNEmptyDataSet'

2. DZNEmptyDataSet 데이터소스 구현하기

DZNEmptyDataSet을 사용하기 위해 해당 뷰 컨트롤러에 DZNEmptyDataSetSource 프로토콜을 채택하고 필요한 메서드를 구현해야 합니다. 아래의 예시 코드는 UITableViewController에서 구현한 예시입니다.

import UIKit
import DZNEmptyDataSet

class MyTableViewController: UITableViewController, DZNEmptyDataSetSource {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // DZNEmptyDataSet의 데이터소스로 self 지정
        self.tableView.emptyDataSetSource = self
    }
  
    // DZNEmptyDataSetSource 메서드 구현
    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        return UIImage(named: "emptyStateImage")
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        let attributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.boldSystemFont(ofSize: 18.0),
            .foregroundColor: UIColor.darkGray
        ]
        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 buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> NSAttributedString? {
        let attributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 16.0),
            .foregroundColor: UIColor.white
        ]
        
        let buttonTitle = "버튼 스타일 변경하기"
        
        return NSAttributedString(string: buttonTitle, attributes: attributes)
    }
    
    func emptyDataSet(_ scrollView: UIScrollView, didTapButton button: UIButton) {
        // 버튼이 탭되었을 때의 동작 구현
        print("빈 상태뷰 버튼 탭됨")
    }
    
}

위의 코드에서 buttonTitle(forEmptyDataSet:for:) 메서드를 사용하여 빈 상태뷰의 버튼의 텍스트 및 스타일을 변경할 수 있습니다. 이 메서드를 구현하여 원하는 버튼 스타일을 설정해주면 됩니다. 버튼이 탭되었을 때의 동작은 emptyDataSet(_:didTapButton:) 메서드를 사용하여 구현할 수 있습니다.

3. 결과 확인하기

위의 코드를 통해 DZNEmptyDataSet을 사용하여 빈 상태뷰의 버튼 스타일을 변경할 수 있습니다. 실행해보면 빈 상태뷰에는 설정한 이미지, 제목, 설명, 그리고 커스텀한 버튼이 나타납니다. 버튼을 탭하면 “빈 상태뷰 버튼 탭됨”이라는 로그가 출력됩니다.

DZNEmptyDataSet을 사용하면 앱의 사용자 경험을 향상시키고, 데이터가 없는 상태를 보다 직관적으로 처리할 수 있습니다.