[240109] Today I Learned

YoungHyun Kim·2024년 1월 9일
1

TIL ✍️

목록 보기
32/68

Todo

1. 데이터 바탕으로 TableView section 나누어 보여주기

struct Todo {
    var id: Int
    var title: String
    var isCompleted: Bool
    var category: String
}

위의 구조체의 category 값에 따라서 tableView의 section을 나누어서 tableViewCell들을 그려보자...

일단 Todo 구조체 내부의 category 변수를 사용해서 tableView의 section을 나눠주기 위해서 딕셔너리 형태의 sections 변수를 정의해준다.

var sections: [String: [Todo]] = [:]

sections 딕셔너리의 key값은 Todo 구조체 내부의 category 값이 될 것..!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        for todo in todoList {
            if sections[todo.category] == nil {
                sections[todo.category] = [todo]
                userDefault.setValue(todo.title, forKey: "\(todo.id)")
            } else {
                sections[todo.category]?.append(todo)
                userDefault.setValue(todo.title, forKey: "\(todo.id)")
            }
        }
    }

view가 로드되었을 때, todo에 미리 적어둔 값들을 사용해서 아까 새로 정의한 sections 딕셔너리에 값들을 적절하게 저장해준다.
코드를 보면 sections의 키 값에 todo.category 값이 미리 있으면 배열에 append, 없으면 배열 자체를 [todo]로 선언해준다.

그리고 나는 내일배움캠프 앱개발 숙련 개인과제의 필수 구현 기능에 Todo값을 UserDefault에 저장해야 하기 때문에 UserDefault.Standard.setValue() 메소드를 같이 적어주었다.
이런 식으로 sections 딕셔너리를 구성하고 나면, 이제 셀을 그려줘야하는데...

// 1. section의 갯수
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.keys.count
    }
    
// 2. section의 title(Header에 적힐 값)
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return Array(sections.keys)[section]
    }

// 3. section별 그려질 cell의 갯수
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let category = Array(sections.keys)[section]
        return sections[category]?.count ?? 0
    }

주석 1번에서 section 자료의 key값의 갯수만큼 tableView의 section 수를 정의한다.
주석 2번 아래의 tableView함수에서는 section.key값들을 가지고 배열을 만들고, 이 배열의 section을 인덱스로 가지는 값이 Header에 적히게 된다.
주석 3번 아래의 tableView 함수에선, section의 Header title값을 category 상수에 저장하고, category 값이 Key값인 sections 딕셔너리의 value 값의 갯수가 섹션의 row 수가 된다.

profile
iOS 개발자가 되고 싶어요

0개의 댓글