본문 바로가기

iOS

[iOS] TableView만드는 첫번째 방법(feat. 임의의 Cell 지정)

1. 스토리보드에 테이블뷰를 생성하고 크기를 정해준다.

2. TableView의 @IBOutlet을 지정해준다.

 

3. UITableDelegate와 DataSource 프로토콜을 채택해준다.
4. 프로토콜에 준수하는 메서드 두개를 생성받아 내부를 구현해준다.

5. tableView메서드들의 주체를 self로 설정해준다. 

 


전체 코드

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var TableViewMain: UITableView!
    
    let explain =
    """
    1. 어떤 데이터인지 ? -> 전화번호부
    2. 테이블의 행 데이터 개수는 몇개인가? -> 100
    3. (옵션) 데이터 행을 눌렀을때 이벤트 설정
    """
    override func viewDidLoad() {
        super.viewDidLoad()
        // tableView메서드를 만들었으면 주체를 정해줘야한다.
        setTableViewMainEqualSelf()
    }
}

// MARK: Method
extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 행의 데이터 개수
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 어떤 데이터인지? 그리고 몇번을 반복할 것이냐?
        // 1. 임의의 셀을 만든다.
        let cell = UITableViewCell.init(style: .default,
                                        reuseIdentifier: nil)
        // indexPath.row를 접근하여 몇번째 인덱스의 행인지의 값을 알 수 있어 값을 표시해준다.
        cell.textLabel?.text = "\(indexPath.row)"
        // 값 반환
        return cell
    }
    
    func setTableViewMainEqualSelf() {
        // 3. tableView를 만든 주체를 self(뷰컨내 메서드들)로 지정해준다.
        TableViewMain.delegate = self
        TableViewMain.dataSource = self
    }
}

 

# 실행 화면

 


# Reference

- https://www.youtube.com/watch?v=5ejngRFNy_k