[4주차] TableView & CollectionView

Seoyoung Lee·2023년 1월 13일
0

UMC

목록 보기
4/8
post-thumbnail

Standard Mission
TableView를 활용한 메모장 앱 구현하기
✅ TableViewCell에 데이터 넣기
✅ 특정 Index번호의 Cell에만 특징을 주고, Cell 재사용 문제 해결해보기

결과 화면

아이폰 메모 앱을 참고해서 구현

TableViewCell에 데이터 넣기

// 데이터모델
struct MemoDataModel {
    var title: String
    var date: String
    var content: String
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "MemoCell") as? MemoTableViewCell else {
            return UITableViewCell()
        }
        
        let data = memoData[indexPath.row]
        
        cell.titleLabel.text = data.title
        cell.dateLabel.text = data.date
        cell.contentLabel.text = data.content
        
        return cell
    }

Cell 재사용 문제 해결

if indexPath.row == 3 {
	let config = UIImage.SymbolConfiguration(scale: .large)
	cell.heartButton.setImage(UIImage(systemName: "heart.fill")?.withConfiguration(config), for: .normal)
}

cellForRowAt 메소드에서 4번째 cell의 우측 버튼 이미지만 꽉 찬 하트 이미지로 설정하였다.

// MemoTableViewCell.swift
override func prepareForReuse() {
	super.prepareForReuse()
	let config = UIImage.SymbolConfiguration(scale: .large)
	heartButton.setImage(UIImage(systemName: "heart")?.withConfiguration(config), for: .normal)
}

cell 재사용 문제를 해결하기 위해 커스텀 셀 스위프트 파일에서 prepareForReuse 메소드를 사용하였다.

챌린지 미션

Challenge Mission
TableView Swipe기능 구현하기

leading swipe action과 trailing swipe action을 구현했다.

leading action

	func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let action = UIContextualAction(style: .normal, title: "위로🆙", handler: {
            action, view, completionHandler in
            self.memoData.insert(self.memoData[indexPath.row], at: 0)
            self.memoData.remove(at: indexPath.row+1)
            tableView.moveRow(at: indexPath, to: IndexPath(row: 0, section: 0))
            completionHandler(true)
        })
        
        action.backgroundColor = .systemGreen
        
        return UISwipeActionsConfiguration(actions: [action])
    }

leading에는 스와이프한 cell을 맨 위로 옮기는 action을 추가했다.

trailing action

	func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let action = UIContextualAction(style: .normal, title: "지워요?🥺", handler: { action , view, completionHandler in
            self.memoData.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .automatic)
            completionHandler(true)
        })
        
        action.backgroundColor = .red
        
        return UISwipeActionsConfiguration(actions: [action])
    }

trailing에는 스와이프한 cell을 삭제하는 action을 추가했다.

UIContextualAction의 handler에서 마지막에 항상 completionHandler(true) 를 넣어줘야 하는 것 같은데 아직 정확한 이유가 잘 와닿지 않는다🥲

profile
나의 내일은 파래 🐳

0개의 댓글