기어가더라도 제대로

[UIKit-기초] UITableView 상단 영역까지 꽉 채우기 본문

UIKit 기초

[UIKit-기초] UITableView 상단 영역까지 꽉 채우기

Damagucci-juice 2025. 1. 25. 08:00

배경 설명

UITableView를 상태바 부분까지 가득 채우고 싶을 때 그것을 하는 방법,

SwiftUI로 리스트를 가득 채우기

->  2025.01.22 - [SwiftUI - 기초] - [SwiftUI-기초] NavigationTitle 수동으로 inline 만들기(with. ToolbarItem)

 

[SwiftUI-기초] NavigationTitle 수동으로 inline 만들기(with. ToolbarItem)

결과물 미리보기문제 상황커머스의 상품의 디테일 페이지 같은 경우 스크롤뷰가 있고 그 안에 이미지가 top 부분 safeArea를 넘어 자리하는 경우가 있다. 이 때 타이틀을 어디에 넣어야 적절한지

damagucci-juice.tistory.com

 

완성된 화면

 

사전 작업 

Auto-layout 구현 편의를 위해 SnapKit을 사용

import UIKit
import SnapKit

class ExTableViewController: UIViewController {

뷰컨트롤러에 테이블을 선언하고 무지개색을 순서대로 Cell에 담기 위해 데이터로 사용할 Color의 배열을 선언

class ExTableViewController: UIViewController {

    let tableView = UITableView()
    let colors = [UIColor.red, .orange, .yellow, .green, .blue, .systemBlue, .purple, .magenta]

    override func viewDidLoad() {

 

viewDidLoad에서 레이아웃과 속성을 설정

    override func viewDidLoad() {
        super.viewDidLoad()

        setupLayout()
        setupAttributes()
    }

 

레이아웃에선 테이블뷰가 화면의 전체를 차지하겠다는 내용이고, 속성 선언에서는 배경뷰 색상을 white로 선언

테이블뷰의 델리게이트와 데이터 소스를 선언

        tableView.contentInsetAdjustmentBehavior = .never

이 명령어가 핵심이다. 

    func setupLayout() {
        view.addSubview(tableView)

        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    func setupAttributes() {
        view.backgroundColor = .white

        tableView.dataSource = self
        tableView.contentInsetAdjustmentBehavior = .never
    }

 

UITableViewDataSource를 채택하고 Cell의 개수는 50개

Cell의 배경색에 무지개색을 채색

구현 편의를 위해 간단한 기본 UITableViewCell을 사용

extension ExTableViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        50
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.backgroundColor = colors[indexPath.row % colors.count]
        return cell
    }
}

 

 

전체 코드

https://gist.github.com/Damagucci-Juice/d30bbc22d14861b96ff1454341ff776b

 

ExFullTableViewController.swift

GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

Comments