iOS/Swift 어플 따라하기

[Swift] chat에서 발신자와 수신자 구별

Chafle 2022. 9. 7. 18:49
반응형

Chat에서 발신자와 수신자를 구별하기

 

ChatViewController에서 tableview의 cell에서 메시지의 발신자는 현재 로그인 한 사용자와 동일

로드 중인 현재 메시지는 현재 사용자이고, 우리가 정한 스타일의 셀로 표시

 

현재 사용자와 동일하지 않은 경우 다른 스타일로 표시해야함

1. 두 개의 다른 메시지 셀을 갖거나

2. 단일 메시지 작업을 할 경우 셀을 선택하고 보낸 사람에 따라 다르게 스타일을 지정한다.

 

2번으로 해보면

 

 

MessageCell.xib파일로 이동해서 UI수정을 하고

 

 

원리는 

메시지의 발신자가 현재 메시지의 이메일 주소와 같은지 비교하고

맞다면 me이미지와 메시지를 보게 하고 다르다면 you이미지를 보이게 한다.

 

 

 

ChatViewController에 가서 tableVeiw셀 메서드에서 코드를 작성한다.

 

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let message = messages[indexPath.row]
        
        let cell = tableView.dequeueReusableCell(withIdentifier: K.cellIdentifier, for: indexPath)
        as! MessageCell // superclass as! Subclass
        cell.label.text = message.body
        
        //This is a messsage from the current user
        if message.sender == Auth.auth().currentUser?.email {
            cell.leftImageView.isHidden = true
            cell.rightImageView.isHidden = false
            cell.messageBubble.backgroundColor = UIColor(named: K.BrandColors.lightPurple)
            cell.label.textColor = UIColor(named: K.BrandColors.purple)
            
        }
       //this is a message from another sender.
        else {
            cell.leftImageView.isHidden = false
            cell.rightImageView.isHidden = true
            cell.messageBubble.backgroundColor = UIColor(named: K.BrandColors.purple)
            cell.label.textColor = UIColor(named: K.BrandColors.lightPurple)
        }
        return cell
    }

 

 

 

반응형