dequeueReusableCell에서 사용하기 위하여!
func configure(_ chat: Chat) {
thumbnail.image = UIImage(named: chat.name)
nameLabel.text = chat.name
chatLabel.text = chat.chat
dateLabel.text = chat.date
위와 같이 빨간색의 오류가 나오게 된다. protocol을 만족하기 위하여 추가적으로 설정해주는 과정이다
첫번째 -> 몇개의 셀이 필요한가?
두번째 -> 해당 셀에 무슨 셀을 표시할 것 인가?
첫번째 func을 위해서는 chatList라는 상수를 아래와 같이 만들어줘야된다.
let chatList: [Chat] = Chat.list
아래와 같이 DataSource를 설정해 줄 수 있다.
width: collectionview의 너비
height: 100
으로 설정한다!
DataSource의 두번 째 함수를 완전히 설정하기 위하여 아래와 같은 코드를 작성한다.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 재사용할 셀을 가져오기(identifier을 통하여서)+ 그리고 그 셀을 return한다.
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ChatListCollectionViewCell", for: indexPath) as? ChatListCollectionViewCell else { return UICollectionViewCell()
}
let chat = chatList[indexPath.item]
//// cell을 configure해주어서 최종 업데이트를 해준다. 근데 알다시피 cell은 위에서 collectionview이다. 그래서 위에서의 코드와 같이 as를 통하여 ChatListCollectionViewCell로 casting을 해준다.
cell.configure(chat)
return cell
}
위에서 casting을 한 이유는 configure 함수는 ChatListCollectionViewCell에서 사용되는 함수이다. 따라서 collectionview인 cell을 ChatListCollectionViewCell로 casting을 해주어야지 configure을 사용할 수 있는 것이다!