본문 바로가기

Codes Travel/iOS Boost Course #2019

UITableView - DataSource & Delegate

안녕하세요 :)

iOS 개발자 리치(rich_iosdev)입니다.


공유해드릴 내용은 DataSource & Delegate 입니다.

 

DataSource는 Application의 데이터 모델과 관련있습니다
Delegate는 테이블 뷰의 모양과 동작을 관리하기 때문에 컨트롤러와 관련있습니다

 

DataSource와 Delegate는 UITableView 뿐만 아니라 UICollectionView에서도 거의 비슷한 원리로 활용되고 구현 가능합니다.

이번 포스팅에서는 UITableViewDataSource와 UITableViewDelegate를 설명해보겠습니다.

 

UITableViewDataSource

 

애플 공식 문서에 표기된 정의입니다.

UITableViewDataSource

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

 

데이터를 관리하고 테이블 뷰의 셀을 제공하기 위해 사용하는 오브젝트에 의해 채택된 메서드들?

정도로 해석할 수 있을 것 같습니다.

 

단순히 얘기해서 테이블 뷰의 셀들에 들어갈 데이터를 직접적으로 관리해준다고 보면될 것 같습니다.

공식 문서에 표기된 DataSource의 역할들입니다.

  • Reporting the number of sections and rows in the table.

  • Providing cells for each row of the table.

  • Providing titles for section headers and footers.

  • Configuring the table's index, if any.

  • Responding to user- or table-initiated updates that require changes to the underlying data.

사실 직접 DataSource 메서드들을 소스 코드로 구현 해보면 훨씬 더 이해하기 쉬운 것 같습니다.

 

// MARK: - UITableView DataSoucre
extension WeatherController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  
        let cell  = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.cellId, for: indexPath)
        return cell
  
  	}
}

 

위 코드를 보면 첫번째 메서드는 테이블 뷰 각 섹션에 몇 개의 Row가 들어갈 것인지 테이블 뷰에 알려줄 수 있습니다.

두번째 메서드에서는 테이블 뷰에 셀 생성해서 제공해줄 수 있습니다.

(이 부분에서 셀에 표시되어야 할 데이터를 넘겨주기도 합니다)

 

위 2개의 메서드는 반드시 구현해줘야하는 필수 메서드들입니다!

 

DataSource는'데이터를 관리한다' 라고 기억하면 좋을 것 같습니다.

 

# UITableViewDelegate

UITableViewDelegate

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

 

DataSource와는 또 다르게 테이블 뷰 셀을 사용자가 선택했을 때 작업을 관리하거나,

각 섹션의 헤더나 푸터를 구성,

셀을 삭제 또는 순서를 재구성하는 일,

그리고 다른 테이블에서의 액션들을 수행

  • Create and manage custom header and footer views.

  • Specify custom heights for rows, headers, and footers.

  • Provide height estimates for better scrolling support.

  • Indent row content.

  • Respond to row selections.

  • Respond to swipes and other actions in table rows.

  • Support editing the table's content.

이렇게 공식 문서 상으로 정의가 되어있습니다.

 

DataSource 처럼 구현된 메서드 소스 코드를 보면서 자세히 설명해보겠습니다.

// MARK: - UITableView Delegate
extension WeatherController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

첫번째 메서드는 테이블 뷰 셀의 Row의 높이를 지정해줍니다.

두번째 메서드는 테이블 뷰의 셀을 선택했을 때 다시 선택이 해제되는 코드를 구현한 것입니다.

 

Delegate는 '모양과 동작을 관리한다' 라고 기억하면 좋을 것 같습니다.

 

UITableViewDataSource, UITableViewDelegate는 꼭 직접 테이블 뷰를 구현해서 각 메서드를 사용해보면

좀 더 이해하기 쉬운 것 같습니다.

 

잘 못된 내용이 있다면 댓글 부탁드립니다!

확인해서 수정하도록 하겠습니다

 

끝까지 읽어주셔서 감사합니다 :)

 

Reference

 

[부스트코스] iOS프로그래밍

3) DataSource 와 Delegate?

https://www.edwith.org/boostcourse-ios/lecture/16887/

 

[LECTURE] 3) DataSource와 Delegate? : edwith

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

www.edwith.org

애플 공식 문서

 

https://developer.apple.com/documentation/uikit/uitableviewdatasource

 

UITableViewDataSource - UIKit | Apple Developer Documentation

Protocol UITableViewDataSource The methods adopted by the object you use to manage data and provide cells for a table view. Declarationprotocol UITableViewDataSource OverviewTable views manage only the presentation of their data; they do not manage the dat

developer.apple.com

https://developer.apple.com/documentation/uikit/uitableviewdelegate

 

UITableViewDelegate - UIKit | Apple Developer Documentation

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

developer.apple.com

'Codes Travel > iOS Boost Course #2019' 카테고리의 다른 글

Photos 프레임워크 활용하기!  (0) 2019.08.22
Codable?  (0) 2019.08.05
세그 (Segue) ?  (0) 2019.08.01
뷰의 재사용 이란?  (0) 2019.08.01
UITableViewCell (테이블 뷰 셀)?  (0) 2019.08.01