• Feed
  • Explore
  • Ranking
/
/
    🎨 UIKit & SwiftUI

    [UIKit] UITableView에서 데이터 없을 때 메시지 표시하기

    Swiftios
    지
    지성
    2025.02.11
    ·
    2 min read

    To Do List 앱을 개발중에, UITableView 에 데이터가 없을 때 "할 일을 추가하라"는 메시지를 중앙에 표시하고 싶었다.

    (예를 들면, 아래 배민의 장바구니 같은?)

    3362

    하지만 UITableView 에는 Empty State를 자동으로 처리하는 기능이 없기에 아래의 방법으로 직접 구현을 시도했다.

    1. UITableViewCell 을 만들어서 Empty 상태의 메시지 추가: 사용자가 리스트를 추가할 경우 기존 셀을 지워야하는 불필요한 리소스 발생

    2. Header View 또는 Footer View 에 메시지 추가: 마찬가지로 불필요한 리소스 발생

    해결 방안

    1. UITableView 의 backgroundView 에 UILabel 설정

      func emptyStateMessage() {
          if tasks.isEmpty {  // 데이터가 없을 경우
              let messageLabel = UILabel()
              messageLabel.text = "아직 할 일이 없어요."
              messageLabel.textAlignment = .center
              messageLabel.font = UIFont.systemFont(ofSize: 18, weight: .medium)
              messageLabel.textColor = .gray
              messageLabel.numberOfLines = 0
              
              tableView.backgroundView = messageLabel
          } else {
              tableView.backgroundView = nil  // 데이터가 있으면 메시지 제거
          }
      }
    2. UITableView 의 데이터가 업데이트 될 때 함수 호출

      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          emptyStateMessage()  // 데이터 변경 시 Empty Message 업데이트
          return tasks.count
      }






    - 컬렉션 아티클