iOS APP 만들기(채팅 리스트) #2

longlivedrgn·2022년 7월 4일
0

APP-채팅 리스트

목록 보기
2/4
post-thumbnail

CollectionViewCell class cocoa file 만들기

CollectionViewCell이랑 CollectionViewCell class랑 연결해주기

identifier도 같은 이름으로 설정

dequeueReusableCell에서 사용하기 위하여!

CollectionViewCell에 update할 element들 연결해주기

클래스 안에 update하는 함수인 configure 함수 정의하기

func configure(_ chat: Chat) {
        thumbnail.image = UIImage(named: chat.name)
        nameLabel.text = chat.name
        chatLabel.text = chat.chat
        dateLabel.text = chat.date

ChatListViewController 설정해주기(Update)

CollectionView를 viewcontroller에 element 생성해주기

참조를 누가하는지 설정하기


위와 같이 빨간색의 오류가 나오게 된다. protocol을 만족하기 위하여 추가적으로 설정해주는 과정이다

DataSource 설정해주기

첫번째 -> 몇개의 셀이 필요한가?
두번째 -> 해당 셀에 무슨 셀을 표시할 것 인가?

첫번째 func을 위해서는 chatList라는 상수를 아래와 같이 만들어줘야된다.

    let chatList: [Chat] = Chat.list

아래와 같이 DataSource를 설정해 줄 수 있다.

Layout 설정해주기

width: collectionview의 너비
height: 100
으로 설정한다!

DataSource 세부설정

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을 사용할 수 있는 것이다!

0개의 댓글

관련 채용 정보