본문 바로가기
iOS, Swift 개발

Swift에서 UITableViewCell을 구현하는 방법

by Nin J 2025. 3. 7.

1. 기본 개념


UITableView: 테이블 뷰는 데이터를 행(row) 단위로 표시하는 뷰.
UITableViewCell: 각 행에 해당하는 개별 셀로, 텍스트, 이미지, 버튼 등을 포함할 수 있다.
필요한 프로토콜: UITableViewDataSource와 UITableViewDelegate를 채택해 데이터 제공과 셀 동작을 정의한다.

Swift에서 UITableView는 리스트 형태의 UI를 구현하는 데 많이 사용된다.

개별 행(Cell)은 UITableViewCell을 활용하여 다양한 데이터를 표시할 수 있다.

1. 기본 UITableView 설정
먼저 UITableView를 추가하고, dataSource 및 delegate를 설정한다.

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    let tableView = UITableView()

    let items = ["Apple", "Banana", "Cherry", "Grape", "Pineapple"]

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.frame = view.bounds
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        
        view.addSubview(tableView)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = items[indexPath.row]
        return cell
    }
}

설명:
- numberOfRowsInSection: 데이터 개수만큼 행을 반환한다.
- cellForRowAt: 각 셀에 데이터를 채운다.

실행 결과
기본적인 UITableView가 표시된다.

2. 커스텀 UITableViewCell 만들기


기본 UITableViewCell 대신 이미지와 텍스트를 포함하는 커스텀 셀을 만든다.

import UIKit

class CustomCell: UITableViewCell {
    
    let cellImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()
    
    let titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.boldSystemFont(ofSize: 16)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        addSubview(cellImageView)
        addSubview(titleLabel)
        
        NSLayoutConstraint.activate([
            cellImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
            cellImageView.centerYAnchor.constraint(equalTo: centerYAnchor),
            cellImageView.widthAnchor.constraint(equalToConstant: 40),
            cellImageView.heightAnchor.constraint(equalToConstant: 40),
            
            titleLabel.leadingAnchor.constraint(equalTo: cellImageView.trailingAnchor, constant: 10),
            titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
        ])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

실행 결과
이미지와 텍스트가 포함된 커스텀 UITableViewCell이 표시된다.

3. UITableView 클릭 이벤트 추가


각 셀을 클릭했을 때 알림창을 띄우는 기능을 추가한다.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedItem = items[indexPath.row]
    
    let alert = UIAlertController(title: "선택한 항목", message: "\(selectedItem.text) 선택됨", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "확인", style: .default))
    
    present(alert, animated: true, completion: nil)
}

 

4. 추가 기능


이미지 로딩 최적화: 네트워크에서 이미지를 가져오는 경우 URLSession이나 SDWebImage 같은 라이브러리를 사용하면 이미지도 가져올수 있다.

if let url = URL(string: "https://example.com/image.jpg") {
    URLSession.shared.dataTask(with: url) { data, _, _ in
        if let data = data, let image = UIImage(data: data) {
            DispatchQueue.main.async {
                cell.customImageView.image = image
            }
        }
    }.resume()
}



셀 선택 처리:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Selected: \(items[indexPath.row].0)")
    tableView.deselectRow(at: indexPath, animated: true)
}

 

 

최종 정리

  1. 기본적인 UITableView 설정
  2. 커스텀 UITableViewCell 구현 (이미지 + 텍스트)
  3. 셀 클릭 이벤트 추가

이제 UITableView를 활용하여 다양한 UI를 만들 수 있다.