본문 바로가기

iOS

[iOS] 테이블 뷰 (TableView) - DataSource, Delegate

TableView DataSource, Delegate

 

 

DataSource와 Delegate

DataSource : 데이터를 받아 이를 뷰에 그려주는 역할 ➡️ 무엇을 어떻게 보여줄 것인가?

Delegate : 동작을 제시 ➡️ 사용자가 보이는 것들 중 무언가에 대한 액션을 취한다면 그에 대한 동작 수행

DataSource는 MVC 중 모델과 관련되어 있고, Delegate테이블뷰의 동작과 모양을 관리하기 때문에 컨트롤러의 역할과 가깝다.

 

 

 

 

UITableViewDataSource

The methods adopted by the object you use to manage data and provide cells for a table view.

protocol UITableViewDataSource
 @required 
 // 특정 위치에 표시할 셀을 요청하는 메서드
 func tableView(UITableView, cellForRowAt: IndexPath) 
 
 // 각 섹션에 표시할 행의 개수를 묻는 메서드
 func tableView(UITableView, numberOfRowsInSection: Int)
 
 @optional
 // 테이블뷰의 총 섹션 개수를 묻는 메서드
 func numberOfSections(in: UITableView)
 
 // 특정 섹션의 헤더 혹은 푸터 타이틀을 묻는 메서드
 func tableView(UITableView, titleForHeaderInSection: Int)
 func tableView(UITableView, titleForFooterInSection: Int)
 
 // 특정 위치의 행을 삭제 또는 추가 요청하는 메서드
 func tableView(UITableView, commit: UITableViewCellEditingStyle, forRowAt: IndexPath)
 
 // 특정 위치의 행이 편집 가능한지 묻는 메서드
 func tableView(UITableView, canEditRowAt: IndexPath)

 // 특정 위치의 행을 재정렬 할 수 있는지 묻는 메서드
 func tableView(UITableView, canMoveRowAt: IndexPath)
 
 // 특정 위치의 행을 다른 위치로 옮기는 메서드
 func tableView(UITableView, moveRowAt: IndexPath, to: IndexPath)

@required : 테이블 뷰를 만들기 위해서 반드시 구현해야 함 ! (해당 프로토콜을 채택했으면 필수로 구현해야하는 함수)

데이터 소스는 테이블 뷰를 생성하고 수정하는 데 필요한 정보를 테이블 뷰 객체에 제공한다.

데이터 소스는 데이터 모델의 델리게이트로, 테이블 뷰의 시각적 모양에 대한 최소한의 정보를 제공한다.

UITableView 객체에 섹션과 행의 수를 알려주며, 행 삽입, 삭제 및 재정렬 기능을 선택적으로 구현할 수 있다.

 

 

 

UITableViewDelegate

Methods for managing selections, configuring section headers and footers, deleting and reordering cells, and performing other actions in a table view.

protocol UITableViewDelegate
// 특정 위치 행의 높이를 묻는 메서드
 func tableView(UITableView, heightForRowAt: IndexPath)
 // 특정 위치 행의 들여쓰기 수준을 묻는 메서드
 func tableView(UITableView, indentationLevelForRowAt: IndexPath)

 // 지정된 행이 선택되었음을 알리는 메서드
 func tableView(UITableView, didSelectRowAt: IndexPath)

 // 지정된 행의 선택이 해제되었음을 알리는 메서드
 func tableView(UITableView, didDeselectRowAt: IndexPath)

 // 특정 섹션의 헤더뷰 또는 푸터뷰를 요청하는 메서드
 func tableView(UITableView, viewForHeaderInSection: Int)
 func tableView(UITableView, viewForFooterInSection: Int)

 // 특정 섹션의 헤더뷰 또는 푸터뷰의 높이를 물어보는 메서드
 func tableView(UITableView, heightForHeaderInSection: Int)
 func tableView(UITableView, heightForFooterInSection: Int)

 // 테이블뷰가 편집모드에 들어갔음을 알리는 메서드
 func tableView(UITableView, willBeginEditingRowAt: IndexPath)

 // 테이블뷰가 편집모드에서 빠져나왔음을 알리는 메서드
 func tableView(UITableView, didEndEditingRowAt: IndexPath?)

Delegate 는 테이블 뷰의 시각적인 부분 수정, 행의 선택 관리, 액세서리 뷰 지원, 개별 행 편집을 도와준다.

Delegate 메소드를 활용하면 테이블 뷰의 세세한 부분을 조정할 수 있음

 

 

reloadData() : Reloads the rows and sections of the table view.

섹션과 관계 없이 모든 데이터를 갱신 ➡️ 비효율적

func reloadData()

 

reloadSections(_:with:) : Reloads the specified sections using a given animation effect.

특정 섹션의 데이터만 갱신, 애니메이션 적용

func reloadSections(_ sections: IndexSet, 
               with animation: UITableView.RowAnimation)
// 섹션에 관계없이 모든 데이터를 reload
self.tableView.reloadData()

// 2번째 section의 데이터만 reload, 애니메이션 적용
self.tableView.reloadSections(IndexSet(2...2 ), with: UITableView.RowAnimation.automatic )

 


 

class rootViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    
    let cellIdentifier: String = "cell"
    let food: [String] = ["쌀국수", "카레", "막창", "순대국밥"]
    let drink: [String] = ["커피", "콜라", "생맥주"]
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0 :
            return food.count
        case 1:
            return drink.count
        default :
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        switch section {
        case 0 :
            return "HEADER food"
        case 1 :
            return "HEADER drink"
        default :
            return "default"
        }
    }
    
    func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
        switch section {
        case 0 :
            return "FOOTER 음~맛있다"
        case 1 :
            return "FOOTER 음~시원하다"
        default :
            return "default"
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath)
        let text: String = indexPath.section == 0 ? food[indexPath.row] : drink[indexPath.row]
        cell.textLabel?.text = text
        return cell
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }


}

 

 

 

 

 

 

iOS ) DataSource와 Delegate의 차이?

 DataSource VS Delegate DataSource는 데이터를 받아 뷰를 그려주는 역할을 한다고 생각하면 됩니다. 너는 뭘 어떻게 보여줄거냐? 그것을 해주는것이 DataSource. TableView를 예로 들자면, DataSource메소..

zeddios.tistory.com

 

 

[LECTURE] 3) DataSource와 Delegate? : edwith

DataSource와 Delegate? 테이블뷰가 필요로하는 DataSource와 Delegate 무엇인지에 대해 알아봅니다. 학습 목표 1. 테이블뷰 데이터 소스와 델리게이트에 ... - 부스트코스

www.edwith.org

 

'iOS' 카테고리의 다른 글

[iOS] UIActivityIndicatorView  (0) 2020.06.11
[iOS] 뷰의 재사용  (0) 2020.06.11
[iOS] 디자인 패턴 | MVC  (0) 2020.06.10
[iOS] Foundation  (0) 2020.06.10
[iOS] UIKit  (0) 2020.06.10