Jiwift

[iOS/Swift] SnapKit UITableView 선언 기초 본문

라이브러리/SnapKit

[iOS/Swift] SnapKit UITableView 선언 기초

지위프트 2024. 1. 14. 20:03
반응형

 

사진과 같이 화면 전체를 덮는 TableView를 생성하겠습니다. 간단한 코드 몇줄로 끝내기.

 

lazy var tableView: UITableView = {
    let tableView: UITableView = UITableView()
    tableView.backgroundColor = .orange
    return tableView
}()

 우선 테이블 뷰를 선언해줍니다.

 

self.view.addSubview(self.tableView)

self.tableView.snp.makeConstraints {
    $0.top.leading.trailing.bottom.equalToSuperview()
}

 그리고 원하는 위치에서 선언과 제약 조건을 걸어줍니다. 

 

 이러면 기본적으로 화면에 표시됩니다. 

 

lazy var tableView: UITableView = {
    let tableView: UITableView = UITableView()
    tableView.backgroundColor = .orange
    tableView.delegate = self
    tableView.dataSource = self
    return tableView
}()

 TableView를 선언할 때 Delegate도 같이 해주면 코드 관리가 편해집니다. 

 

 

 

 

 

//
//  ViewController.swift
//  ExProject
//
//  Created by 김지태 on 1/14/24.
//

import UIKit
import SnapKit

class ViewController: UIViewController {

    lazy var tableView: UITableView = {
        let tableView: UITableView = UITableView()
        tableView.backgroundColor = .orange
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
            
        self.view.addSubview(self.tableView)
        
        self.tableView.snp.makeConstraints {
            $0.top.leading.trailing.bottom.equalToSuperview()
        }
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
}

extension ViewController: UITableViewDelegate {
    
}

 

 

 

반응형