Group Study (2021-2022)/iOS

[iOS] 4주차 스터디 - TableView, CollectionView

whaeun 2021. 11. 1. 23:53

[ 1 ] 강의 영상

- How to Create TableView : https://youtu.be/C36sb5sc6lE
- TableView Custom Cells : https://youtu.be/R2Ng8Vj2yhY
- Create CollectionViews : https://youtu.be/eWGu3hcL3ww

 

[ 2 ] 스터디 내용

1. TableView

(1) TableView란?

표의 각 행에 앱 콘텐츠 중 하나를 포함하여 세로 스크롤하는 내용의 행을 하나의 열에 표시하는 것.

 

(2) TableView 사용하기

- View Controller에 Table View를 위치시키고 Constraint를 설정한다. Table View의 Prototype Cells를 필요한 만큼 증가시킨다. 각각의 Cell 별로 해당 Cell을 사용하고자 할 때 호출할 수 있도록 하는 identifier를 설정해 준다.

* Prototype Cell?
각 테이블에서 Label, Image, Switch 등의 데이터들이 어디에 위치할지 정의해주는 템플릿

- 각 Cell 별로 ImageView, Button, Label 등의 요소들을 제어하기 위해 Cell Class를 만듭니다. Cocoa Touch Class 파일을 새로 만든 후 UITableViewCell로 선택하고 각각의 요소들을 선언해 줍니다. 이렇게 만들어진 Cell Class를 Cell의 Custom Class로 연결해 줍니다. 그 후 Cell의 Outlets에서 각각 선언한 부분들이 실제 셀에서의 요소들과 매칭되도록 control + drag로 이어줍니다. 

import UIKit

class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var alarmLabel: UILabel!
    @IBOutlet weak var toggleSwitch: UISwitch!
}

- 해당 Table View가 위치한 View Controller에도 Custom Class를 연결해 주어 각 Table에서 Cell 양식에 따라 각각의 Cell들이 나타날 수 있도록 한다. @IBOutlet var table: UITableView!를 해주고 마찬가지로 화면의 Table View와 control + drag로 이어준다. 

import UIKit

class AlarmController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet var table: UITableView!
    
    // Table View 내에서의 section 구분 설정 
    private let sections: [String] = ["기타", "업무"]
    
    // Cell 내의 요소들을 구조체로 정의
    struct Alarm {
        let title: String
        let content: String
        let toggleSwitch: Bool
    }
    
    let data: [Alarm] = [
        Alarm(title: "오전 7:30", content: "알람", toggleSwitch: false),
        Alarm(title: "오전 8:10", content: "알람", toggleSwitch: false),
        Alarm(title: "오전 8:25", content: "알람", toggleSwitch: false),
        Alarm(title: "오전 8:45", content: "알람", toggleSwitch: false),
        Alarm(title: "오전 9:00", content: "알람", toggleSwitch: false),
        Alarm(title: "오전 9:12", content: "알람", toggleSwitch: false),
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        table.dataSource = self
        table.delegate = self
        
    }
    
    // section의 개수
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

	// 행의 개수
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    // SectionHeader의 이름
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section]
    }

	
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let alarm = data[indexPath.row]
        let cell = table.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
        
        let switchView = UISwitch(frame: .zero)
        switchView.setOn(alarm.toggleSwitch, animated: true)
        switchView.tag = indexPath.row
        
        cell.accessoryView = switchView
        cell.alarmLabel.text = alarm.content
        cell.label.text = alarm.title
        
        return cell
        
    }
    
    // 행의 높이 설정
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
}

- 실행화면

 

(3) TableViewDelegate

TableViewDelegate는 Table View의 모양과 동작을 관리하며 MVC(Model-View-Controller)의 C에 가깝다. TableViewDelegate는 테이블 뷰의 시각적인 부분 수정, 행의 선택 관리, 액세서리 뷰 지원, 테이블 뷰의 개별 행 편집을 도와준다. 필수로 구현해야 하는 메소드는 없다.

 // 특정 위치 행의 높이를 묻는 메서드
 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?)

 

(4) TableViewDataSource

TableViewDataSource는 데이터 모델로 테이블 뷰를 생성하고 수정하는데 필요한 정보를 테이블 뷰 객체에 제공하며 MVC(Model-View-Controller)의 M에 가깝다. UITableView객체에 섹션의 수와 행의 수를 알려주며, 행의 삽입, 삭제 및 재정렬하는 기능을 선택적으로 구현할 수 있다.

*아래의 두 메서드는 필수적으로 구현해야 한다.

 // 특정 위치에 표시할 셀을 요청하는 메서드
 func tableView(UITableView, cellForRowAt: IndexPath) 
 
 // 각 섹션에 표시할 행의 개수를 묻는 메서드
 func tableView(UITableView, numberOfRowsInSection: Int)

* 아래의 메서드는 선택적으로 구현하면 된다.

 // 테이블뷰의 총 섹션 개수를 묻는 메서드
 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)

 

2. CollectionView

(1) CollectionView?

CollectionView는 그리드와 스택, 타일, 원형 배열을 포함하여 다양한 유연성을 제공하는 인터페이스이다. 데이터 아이템의 정렬된 세트를 표시하는 수단으로 사용할 수 있다.

 

(2) CollectionView의 구성요소

- Cell : Collection View의 주요 콘텐츠를 표시한다. Collection View DataSource 객체에서 표시한 Cell에 대한 정보를 가져온다. 

- Supplementary Views : 섹션에 대한 정보를 표시한다.  사용되는 레이아웃 객체에서 사용법과 배치방식을 제어한다.

- Decoration Views : 콘텐츠가 스크롤 되는 Collection View에 대한 배경을 꾸밀 때 사용한다.

- Layout Object : Collection View 내의 아이템 배치 및 시각적 스타일을 결정한다. 

 

(3) CollectionViewDelegate

  // 지정된 셀이 사용자에 의해 선택될 수 있는지 묻는 메서드
  optional func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool

  // 지정된 셀이 선택되었음을 알리는 메서드
  optional func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)

  // 지정된 셀의 선택이 해제되었음을 알리는 메서드
  optional func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath)

  // 지정된 셀이 강조될 수 있는지 묻는 메서드
  optional func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool
  
  // 지정된 셀이 강조되었을 때 알려주는 메서드
  optional func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath)
  
  // 지정된 셀이 강조가 해제될 때 알려주는 메서드
  optional func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath)

 

(4) CollectionView DataSource

* 아래의 두 메서드는 필수적으로 구현해야 한다.

 // 지정된 섹션에 표시할 항목의 개수를 묻는 메서드
 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int

 // 컬렉션뷰의 지정된 위치에 표시할 셀을 요청하는 메서드
 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

* 아래의 메서드는 선택적으로 구현하면 된다.

  // 컬렉션뷰의 섹션의 개수를 묻는 메서드
  optional func numberOfSections(in collectionView: UICollectionView) -> Int​

  // 지정된 위치의 항목을 컬렉션뷰의 다른 위치로 이동할 수 있는지를 묻는 메서드
  optional func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool

  // 지정된 위치의 항목을 다른 위치로 이동하도록 지시하는 메서드
  optional func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)

 

[ 3 ] 참고 자료

- https://developer.apple.com/documentation/uikit/uitableview
- https://www.ioscreator.com/tutorials/prototype-cells-table-view-ios-tutorial
- https://developer.apple.com/documentation/uikit/uitableviewcell
- https://m.blog.naver.com/jdub7138/220958881556
- https://www.boostcourse.org/mo326/lecture/16860
- https://developer.apple.com/documentation/uikit/uicollectionview