iOS

[iOS] TableViewController - [2]

스벅 보안관 2024. 5. 28. 09:34

안녕하세요 스벅보안관입니다.

지난 시간에는 TableViewController의 기본 개념과 설정에 대해 알아보았습니다. 이번 시간에는 TableViewController의 고급 기능(?)과 예제를 다루어 보겠습니다. 

 

 

약간 있ability하게(있어보인다는 뜻...) 블로그를 작성하고싶은데, 작성하고싶은 개념이 너무 많아 뭔가 딱딱해지는 느낌,,, 

 

 

TableViewController의 고급 기능

 

1. 섹션 추가

TableView는 여러 섹션을 가질 수 있습니다.

각 섹션은 개별적으로 제목을 가질 수 있으며, 섹션 내의 행들을 그룹화할 수 있습니다.

override func numberOfSections(in tableView: UITableView) -> Int {
    return sections.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[section].items.count
}

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sections[section].title
}

 

2. 커스텀 헤더(Header) 및 푸터(Footer)

TableView의 섹션 헤더와 푸터를 UIView를 사용하여 원하는 디자인으로 설정할 수 있습니다.

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView()
    headerView.backgroundColor = .lightGray
    let label = UILabel()
    label.text = sections[section].title
    label.frame = CGRect(x: 16, y: 0, width: tableView.frame.width, height: 40)
    headerView.addSubview(label)
    return headerView
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 40
}

 

 

전체 예제 코드

이제 위의 내용을 바탕으로 간단한 연락처 앱을 만들어보았습니다.

연락처는 이름과 전화번호로 구성되며, 섹션별로 그룹화됩니다.

import UIKit

struct Contact {
    let name: String
    let phoneNumber: String
}

struct ContactSection {
    let title: String
    var contacts: [Contact]
}

class ContactsTableViewController: UITableViewController {

    var sections = [
        ContactSection(title: "A", contacts: [Contact(name: "Alice", phoneNumber: "123-456-7890")]),
        ContactSection(title: "B", contacts: [Contact(name: "Bob", phoneNumber: "987-654-3210")])
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].contacts.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let contact = sections[indexPath.section].contacts[indexPath.row]
        cell.textLabel?.text = contact.name
        cell.detailTextLabel?.text = contact.phoneNumber
        return cell
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section].title
    }
}

 

 

오늘의 결론

반복 또 반복하면서 확실하고 자유자재로 tableView를 활용할 수 있도록 연습해야한다.

 

연습만이 살길...