연습/swift개발

[swift 입문] Dynamic Table View - Data Source

TimeSave 2022. 1. 20. 22:11

 

TableView의 MVC 구조

1. 테이블 뷰가 데이터를 표시하는 방식

 

1.1 numberOfSectionsInTableView : How Many Sections In that Table View?

1.2 numberOfRowsInSection : How Many Rows In that Section

1.3 cellForRowAtIndexPath : What should I display in that (Section, Row)

1.4 TitleForHeaderInSection : Section의 타이틀을 달 수 있다. ex)축구선수 Section

1.5 TitleForFooterInSection : Section의 꼬릿말? 같은것을 달 수 있다. ex)총합 : 95

 

아래 예제에서 return 값을 셋팅해 놓으면 원하는 section & row를 출력하는 테이블 뷰를 만들 수 있다.

 

ex1) return 값이 section 수 이다.

override func numberOfSectionsInTableView(tableView : UITableView) -> Int {

return 1

}

 

ex2) section에 있는 Object(=row) 갯수를 return 한다.

override func tableView(tableView : UITableView, numberOfRowsInSection Section : Int) -> Int{

return objects.count

} //가져올 모델의 count를 넣으면 된다.(섹션별로 모델하나 넣는 가정)

 

ex3) row 에 보여줄 데이터(cell)를 return한다.

overide func tableView(tableView:UITableView, CellForRowIndexPath indexPath: NSIndexPath)

-> UITableViewCell{

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath : indexPath)

//테이블안의 셀을 하나 클릭해서 속성을 보면 Identifier가 있다. 위 함수의 "Cell" 과 같다면 그 Cell은 재활용 한다.

 

let object objects[indexPath.row] as! NSDate //어떤 cell을 return 할 지 값 셋팅하는 부분

cell.textLabel!.text = object.description//어떤 cell을 return할 지 값 셋팅하는 부분

 

 

return cell

}//여기에서 주어지는 IndexPath가 지금순간의 출력하려하는 Section과 row에 관한 정보를 담고 있는 것 같다.

 

 

 

2. DataSource 프로토콜(약속, 규칙)

 

 

 

 

 

 

 

출처 : https://www.youtube.com/watch?v=Li216kdDX-0&list=PLz4XWo74AOacDcJ0hEWvOJAGPme44zrA_&index=32, [iOS Swift입문] Dynamic Table View - DataSource, Programmers