적당한 고통은 희열이다

- 댄 브라운 '다빈치 코드' 중에서

Project/ToyProject_Couple App

[Swift iOS] Custom UITableView 만들기

hongssup_ 2021. 3. 12. 01:46
반응형

테이블뷰 하나만도 커스텀하게 만들기 쉽지 않구나 하는 걸 깨닫게 되었다. 테이블 뷰 굉장히 만만하게 봤는데.. 너 만만하지 않구나? ㅎㅎ

 

1. 테이블 뷰 추가하기

2. extension으로 UITableViewDataSource, UITableViewDelegate 추가해주기 

3. section 갯수, 각 section 당 cell 갯수, 높이 및 각종 속성들 추가

4. UITextField() 이용해서 사용자 입력 받아오기 

5. UITableView 속 cell 내용들 추가

 

기본 테이블뷰 추가해 화면에 띄우기

import Foundation
import UIKit

class AddScheduleViewController: UIViewController {
    
    let tableView = UITableView(frame: .zero, style: .plain)  //1
    var items = ["내용", "날짜", "시간", "위치"]

    override func loadView() {
        super.loadView()
        let view = UIView(frame: UIScreen.main.bounds)
        view.backgroundColor = .systemGray6
        self.view = view
        setupTableView()  //4
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    func setupTableView() {
        //6
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.dataSource = self
        tableView.delegate = self     
        //2
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        //3
        tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    }
}
//5
extension AddScheduleViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    //7
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = items[indexPath.row]
        return cell
    }
}

1. 원하는 스타일의 UITableView 생성하기. 나는 깔끔하게 .plain으로! (UITableView style에는 .plain, .grouped, .insetGrouped가 있다.)

2. setupTableView()에서 tableView를 view에 넣어주고 

3. constraints를 설정해준다. 

4. setupTableView()를 loadView() 에 선언해주고 

5. extension으로 UITableView의 DataSource, Delegate 프로토콜을 추가해준다. numberOfRowsInSection과 cellForRowAt indexPath가 기본적으로 쓰이는 설정들. 

6. tableView의 cell에 새로운 table cell을 register해주고, 앞서 extension으로 추가해준 dataSource와 delegate 속성을 자신에게 넣어준다. cell의 갯수는 item[]의 항목 갯수로, cell에 입력될 text는 items[indexPath.row]로.

 

Custom UITableView _tableView 가지고놀기

1. section 추가 해주고 섹션 별 원하는 값 넣어주기

extension에 numberOfSections() 함수를 추가해주고, 원하는 section의 갯수를 return해준다.

func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}

numberOfRowsInSection에 섹션 별 cell 갯수를 return해준다. 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    if section == 0 {
        return items.count
    } else {
        return 1
    }
}

cellForRowAt indexPath에서 섹션별로 cell 안에 들어갈 내용을 입력해준다. 

UITableView cell에는 자동으로 seletion 되는 기능이 있는데, 이게 싫으면 SelectionStyle을 none으로 설정을 바꿔주면 된다. 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    if indexPath.section == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = items[indexPath.row]
        cell.selectionStyle = UITableViewCell.SelectionStyle.none
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath)
        cell.textLabel?.text = "메모"
        cell.selectionStyle = UITableViewCell.SelectionStyle.none
        return cell
    }
}

2. UITextField() 이용해 사용자 입력값 받아오기

 

섹션 Header 설정

Header 색상 변경 및 글씨 색상 변경

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        let header = view as! UITableViewHeaderFooterView
        header.textLabel?.textColor = UIColor.white
        if #available(iOS 14.0, *) {
            header.backgroundConfiguration?.backgroundColor = .darkGray
        } else {
            header.backgroundView?.backgroundColor = .darkGray
        }
    }

 

+

Cell 삭제 / 추가

참고: cell delete with swipe

 

bounce 방지하기

tableView.bounces = false

tableView.alwaysBounceVertical = false 이렇게 알려주는 데도 있던데 이거는 해도 안되는거같던데 무슨 차이일까..

 

 

UITableView example

728x90
반응형