공식문서

A view that presents data using rows in a single column.

⇒ 단일 열에 배열된 행을 표시하는 뷰

  • 단일 열에 수직 스크롤을 제공하는 콘텐츠 행을 표시
  • 예를 들어 연락처 앱과 설정 앱이 있음
  • 연락처 앱은 일반적인 TableView 를 표시하며, 설정 앱은 Group화 된 TableView를 표시
  • 여러개의 행은 하나의 섹션으로 포함할수 있으며, 섹션은 헤더 와 푸터로 구성

 

구현해보기

1. Storyboard 에서 TableView와 TableViewCell 을 ViewController에 끌어다 놓자

 

2. 이렇게 끌어다 놓아 ViewController에 포함시키고 Cell에 대한 고유 값을 설정해 준다

 

3. cell을 선택한 상태로 오른쪽의 인스펙터 창에서 identifier에 구분할수 있는 이름으로 셀이름을 설정한다

( 예시에서는 "myCell" )

 

4. 해당 viewController 코드 파일에 TableView를 연결한다 ( IBOutlet )

[ storyboard 파일에서 control 을 누르고 코드쪽으로 끌어 당기면 연결된다 ]

 

5. datasource 프로토콜을 채택하고 내용을 구현해 준다

//
//  ViewController.swift
//  tableViewPrac
//
//  Created by Hong jeongmin on 2022/05/19.
//

import UIKit

struct myTableCell {
    var name: String
}

var nameArr = [
    myTableCell(name: "홍길동"),
    myTableCell(name: "이선비"),
    myTableCell(name: "개똥이"),
    myTableCell(name: "새이름"),
    myTableCell(name: "김하나"),
]

class ViewController: UIViewController {
    @IBOutlet weak var myTable: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        // 위임
        myTable.dataSource = self
    }
}

// DataSource => 각 테이블 행의 어떤 내용을 표시할지
extension ViewController: UITableViewDataSource {
    // 몇개의 행을 리턴할지
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nameArr.count
    }
    
    // 각 행에는 어떤 내용을 포함 할지
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "mycell") else {
            fatalError("셀이 존재하지 않습니다.")
        }
        
        cell.textLabel?.text = nameArr[indexPath.row].name
        return cell
    }
    
    // 헤더의 이름 표시
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "헤더입니다"
    }
    
    // 푸터의 이름 표시
    func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
        return "푸터입니다"
    }
    
    // 몇개의 섹션을 구성할 것인지 표시
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
}

6. 결과확인

 

datasource 를 반드시 설정해 주어야 해당 내용이 나타나니 코드를 잘 살펴보자~!

 

테이블뷰 기초 끝!

+ Recent posts