개발하는 동글 :]

[TIL],[UIKit],[TableView],[섹션 분리 후 다른 Cell적용] 본문

카테고리 없음

[TIL],[UIKit],[TableView],[섹션 분리 후 다른 Cell적용]

동글하다 2023. 7. 26. 09:17

적용 화면

ViewDidLoad()

@IBOutlet weak var myTableView: UITableView!
    
    
    var dataManager = DataManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        myTableView.dataSource = self
    }

테이블 뷰 속성을 만들어 주고 , datasource를 자신으로 할당해 준다.

 

extension

extension ViewController: UITableViewDataSource, UITableViewDelegate{
    
    // Section 갯수 지정
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataManager.section.count
    }
    //var section = ["0","1","2"]
    
    // tableView Cell 갯수 지정, 여기서 Section에 따른 구분
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          if section == 0 {
              return dataManager.section0Data.count
          } else if section == 1 {
              return dataManager.section1Data.count
          } else {
              return dataManager.section2Data.count
          }
      }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = myTableView.dequeueReusableCell(withIdentifier: "TableViewUserInfoCell", for: indexPath) as! TableViewUserInfoCell
            return cell
        } else if indexPath.section == 1 {
            let cell = myTableView.dequeueReusableCell(withIdentifier: "TableViewDefalutCell", for: indexPath) as! TableViewDefalutCell
            cell.cellLabel.text = dataManager.section1Data[indexPath.row].name
            cell.cellImageView.image = UIImage(named: dataManager.section1Data[indexPath.row].image)
            cell.cellInfoLabel.text = dataManager.section1Data[indexPath.row].info
            return cell
        } else {
            let cell = myTableView.dequeueReusableCell(withIdentifier: "TableViewDefalutCell", for: indexPath) as! TableViewDefalutCell
            cell.cellLabel.text = dataManager.section2Data[indexPath.row].name
            cell.cellInfoLabel.text = dataManager.section2Data[indexPath.row].info
            return cell
        }
    }
   
    
    
}

tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 메서드를 section에 따라 몇 개의 cell이 나올지 결정해 주고 tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 메서드를 분기처리하여 각각의 section에서 어떠한 cell이 사용될지를 결정한다.