TableView - DataSource

hoBahk·2021년 12월 23일
0

TableView

목록 보기
3/4

안녕하세요
지난 글에 이어서 TableView에 DataSouce를 통해 데이터를 보여주도록 하겠습니다.

UITableViewDataSource 프로토콜에 정의된 메서드를 살펴보도록 하겠습니다.

// Section(섹션)의 개수를 묻는 메서드
optional func numberOfSections(in tableView: UITableView) -> Int // Default is 1 if not implemented
    
// Section(섹션)안에 있는 row(행)의 개수를 리턴해주는 메서드
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int

// 특정위치에 보여줄 셀을 요청하는 메서드
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

// 특정 섹션의 헤더(header)를 묻는 메서드
optional func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?

// 특정 섹션의 푸터(footer)를 묻는 메서드
optional func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String?

// 특정 위치의 행이 편집 가능한지 묻는 메서드
optional func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool

// 특정 위치의 행을 재정렬 할 수 있는지 묻는 메서드
optional func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool

// 특정 위치의 행을 추가 혹은 삭제 요청하는 메서드
optional func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
    
//  특정 위치의 행을 다른 위치로 옮기는 메서드
optional func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
}

많은 메서드들이 있습니다. 그 중 필수구현인 메서드는 optional이 적혀있지 않은 2개 입니다.
오늘은 2가지 메서드만 사용하여 테이블뷰의 데이터소스를 구현해보겠습니다.

먼저 셀을 구성하는 객체를 만들어줍니다.

// TableViewCell.swift
class TableViewCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var subTitleLabel: UILabel!
    
    func setLabel(title: String, subTitle: String) {
        titleLabel.text = title
        subTitleLabel.text = subTitle
    }
}

테스트용 데이터를 만들어줍니다.
저는 딕셔너리로 만들었습니다.

//  TableViewController.swift

// 테스트용 데이터
let data = [0: "호박", 1: "수박", 2: "포도", 3: "딸기", 4: "파인애플"]

필수 구현 메서드를 정의해줍니다.

//  TableViewController.swift

    // 행의 개수를 리턴하는 메서드
    // 테스트용 데이터 data의 count를 리턴
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    // 보여줄 셀을 설정
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as? TableViewCell else {
            return UITableViewCell()
        }
        
        cell.setLabel(title: String(indexPath.row), subTitle: data[indexPath.row]!)
        
        return cell
    }

두번째 메서드를 보면 dequeueReusableCell메서드가 있습니다.
메서드 이름 그대로 재사용할 셀을 디큐하는 것입니다. 즉, 사용했던 셀을 재사용하는 것입니다.
사용한 셀을 왜 재사용할까요?
지금은 5개 밖에 없지만 100개, 1000개가 넘는 테이블뷰의 경우 셀을 만들 때 많은 메모리가 들어가기 때문에 그것을 아끼기 위해 셀을 재사용합니다.
셀을 삭제하고 새로 만드는 것보다 재사용하는 것에 대한 메모리 부담이 적은 것으로 보입니다!!

첫번째 파라미터로 cell의 identifier를 적어줍니다.
두번째 파라미터로 indexPath를 적어줍니다. indexPath는 IndexPath 타입으로 행의 번호를 가르킵니다.

guard let 구문을 통해 cell을 구해줍니다. else문으로 빠지게 되면 빈셀을 보여주게 했습니다.
그리고 나서 TableViewCell 클래스에 구현해 두었던 setLabel 메서드를 호출하여 cell의 요소들에 데이터를 채워주게 합니다.

이렇게 해주면 테이블뷰에 데이터가 보여집니다!

감사합니다.
다음에는 TableView Delegate에 대해서도 알아보겠습니다!!

예제 코드

import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var subTitleLabel: UILabel!
    
    func setLabel(title: String, subTitle: String) {
        titleLabel.text = title
        subTitleLabel.text = subTitle
    }
}
import UIKit

class TableViewController: UIViewController, UITableViewDataSource {
 
    let data = [0: "호박", 1: "수박", 2: "포도", 3: "딸기", 4: "파인애플"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        // Do any additional setup after loading the view.
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as? TableViewCell else {
            return UITableViewCell()
        }
        cell.setLabel(title: String(indexPath.row), subTitle: data[indexPath.row]!)
        
        return cell
    }
}
profile
호박에 줄 그어서 수박 되는 성장 드라마

0개의 댓글