본문 바로가기
Dot/iOS

iOS) tableView(_:cellForRowAt:) / tableView(_:numberOfRowsInSection:)

by jum0 2020. 10. 11.

Table views는 데이터를 보여주는 것만 관리하고, 데이터 그 자체를 관리하지는 않습니다. 데이터를 관리하기 위해서는 table with a data source object를 제공해야 하는데 UITableViewDataSource 프로토콜을 채택하여 구현할 수 있습니다.

대표적인 메서드로 tableView(_:cellForRowAt:)tableView(_:numberOfRowsInSection:)가 있는데, 프로토콜을 채택하면 필수적으로 요구되는 메서드입니다.

사용 예시는 다음과 같습니다.

// Return the number of rows for the table.     
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return 0
}

// Provide a cell object for each row.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   // Fetch a cell of the appropriate type.
   let cell = tableView.dequeueReusableCell(withIdentifier: "cellTypeIdentifier", for: indexPath)
   
   // Configure the cell’s contents.
   cell.textLabel!.text = "Cell text"
       
   return cell
}

tableView(_:cellForRowAt:)

역할은 table view의 특정 위치에 삽입할 셀의 데이터 소스를 요청하는 것입니다.

func tableView(_ tableView: UITableView, 
  cellForRowAt indexPath: IndexPath) -> UITableViewCell

선언은 다음과 같고, 파라미터로 tableView indexPath를 가지는데, tableView는 셀에 요청하는 table-view object를, indexPath는 tableView 내의 row에 위치하는 index path를 의미합니다.

리턴 값으로는 table view가 지정된 row에 사용할 수 있는 UITableViewCell에서 상속된 개체입니다.

부가적으로 index path란 함수가 요청하는 섹션의 행에 대한 정보를 가지고 있는데, 이 숫자를 기준으로 주어진 행에 대한 데이터를 표시하도록 셀을 구성합니다.

그림 1. Table View 예시

그림 1. 의 사진과 같이 테이블이 구성되어 있을 경우, indexPath를 출력해보면, 다음과 같은 값이 나옵니다.

그림 2. indexPath 출력값

왼쪽에 있는 숫자는 section을 나타내고, 오른쪽에 있는 숫자는 셀의 row를 나타냅니다.

그림 3. section 부분

section이란 그림 3. 노란색 동그라미 부분으로 위에서부터 0, 1, 2와 같이 증가됩니다.

tableView(_:numberOfRowsInSection:)

역할은 주어진 table view의 section에서 리턴할 행의 개수를 data source에게 전달합니다.

func tableView(_ tableView: UITableView, 
  cellForRowAt indexPath: IndexPath) -> UITableViewCell

선언은 다음과 같고, 파라미터는 tableView section입니다. tableView셀에 요청하는 table-view object를, section은 tableView 내 section을 식별하는 index 숫자입니다.

리턴 값으로는 section의 행의 개수입니다.


참고 자료

[1] - Apple Developer Documentation UITableViewDataSource  developer.apple.com/documentation/uikit/uitableviewdatasource

[2] - Apple Developer Documentation tableView(_:cellForRowAt:) developer.apple.com/documentation/uikit/uitableviewdatasource/1614861-tableview

[3] - Apple Developer Documentation tableView(_:numberOfRowsInSection:) developer.apple.com/documentation/uikit/uitableviewdatasource/1614931-tableview


수정해야 할 부분이 있다면 알려주세요!

감사합니다!

반응형

댓글