개발...................../TIL

테이블뷰 기본

bluewiper 2024. 7. 19. 09:27

더보기
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var data: [String] = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape", "Honeydew"]
    
    let myTableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .green
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        return tableView
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        myTableView.dataSource = self
        myTableView.delegate = self
        
        view.addSubview(myTableView)
        
        configureTableView()
                
    }
    
    func configureTableView() {
        
        NSLayoutConstraint.activate([
            myTableView.topAnchor.constraint(equalTo: view.topAnchor),
            myTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            myTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            myTableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])
    }
    
    // MARK: - UITableViewDataSource Methods
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        data.count
    }
    
    // MARK: - UITableViewDelegate Methods
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = data[indexPath.row]

        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       
        60
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // 데이터 소스 항목에서 삭제
            data.remove(at: indexPath.row)
            // 테이블 뷰 행에서 삭제
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
    }
}

 

 

테이블뷰를 구성하는 닻으로 기본적으로 이정도는 갖춰야 구현 되는 조건 

 

 

1. UI 인스턴스 생성 및 반환

테이블뷰 인스턴스를 생성해야 이후에 사용할 수 있습니다.

private let tableView: UITableView = {
    let tableView = UITableView()
    return tableView
}()

 

2. 오토레이아웃 비활성화 [UI요소].translatesAutoresizingMaskIntoConstraints = false

오토레이아웃을 사용할 것이므로 자동으로 생성되는 제약을 비활성화해야 합니다.

tableView.translatesAutoresizingMaskIntoConstraints = false

 

3. 서브뷰에 추가 view.addsubView

테이블뷰를 뷰 계층 구조에 추가해야 화면에 보입니다.

view.addSubview(tableView)

 

4. register

테이블뷰에서 사용할 셀을 등록해야 테이블뷰가 셀을 재사용할 수 있습니다.

tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

 

5. delegate, dataSource 생성

테이블뷰의 델리게이트와 데이터 소스를 설정해야 테이블뷰가 데이터를 표시하고 사용자 상호작용을 처리할 수 있습니다.

tableView.dataSource = self
tableView.delegate = self

 

6. numberOfRowsInSection, cellForRowAt

UITableViewDataSource 메서드를 구현해야 테이블뷰가 몇 개의 셀을 표시할지와 각 셀의 내용을 결정할 수 있습니다.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = data[indexPath.row]
    return cell
}