[iOS] UITableView Section 사용하기

doooly·2024년 1월 28일
0

iOS

목록 보기
8/8
post-thumbnail

💡 Section?

UITableView의 section은 header, footer, 내부 셀들로 구성되어있습니다
코드를 통해 관련 설정들을 간략하게 살펴보겠습니다 😎


1️⃣ tableView UI

2차원 배열을 사용해 각 section별로 string 구분
headerList[i]cellList[i] string 배열의 header text로 사용됩니다

let myPageTableView = UITableView(frame: .zero, style: .grouped)

let myPageTableViewCellList : [[String]] = [["자주 가는 역 설정", "즐겨찾는 경로 설정", "푸시 알림"], ["서비스 이용 약관", "개인 정보 처리 방침"], ["로그아웃", "회원 탈퇴"]]
let myPageTableViewHeaderList : [String] = ["설정", "앱 정보", "계정 관리"]

2️⃣ tableView Delegate, DataSource

extension MyPageViewController : UITableViewDelegate, UITableViewDataSource {

	//각 섹션마다 나타낼 cell 개수
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myPageTableViewCellList[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myPageTableViewCell")
        ?? UITableViewCell(style: .default, reuseIdentifier: "myPageTableViewCell")
        
        //section 번호에 해당하는 행에 접근 후 row 번호로 열 접근
        cell.textLabel?.text = myPageTableViewCellList[indexPath.section][indexPath.row]
        cell.textLabel?.font = UIFont.systemFont(ofSize: 15)
        cell.textLabel?.textColor = .darkGray
        cell.backgroundColor = .background
        cell.accessoryType = .disclosureIndicator
        return cell
    }
   

numberOfRowsInSection 함수에선 아래와 같은 귀찮은 로직 대신 배열을 사용해 섹션 당 셀의 개수를 반환해줍니다

 switch section{
        case 0:
            return 3
        case 1:
            return 2
        case 2:
            return 2
        default:
            return 0
        }

3️⃣ header 설정

    //section 개수
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }

	//header list에서 해당하는 section 번호로 인덱스 접근
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return myPageTableViewHeaderList[section]
    }
    
    //header 두께 설정
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }

저는 footer를 divider로 연출하기 위해 footerView를 UIView()로 설정했습니다
또한 마지막 section footer을 없애기 위해 두께를 0으로 지정해줬습니다

    //사용할 view 설정
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: .zero)
        footerView.backgroundColor = .divider
        return footerView
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if(section == 2){
            return 0
        } else {
            return 3
        }
    }


📱 결과 화면

0개의 댓글