2016-12-02 47 views
0

我正在顯示接收者的發件人名稱。但是,我不希望在該人發送的每個文本上顯示該名稱。例如,如果他/她連續發送消息,我只希望它在第一條消息的頂部顯示名稱。我會在這裏提供我的聊天截圖:Swift JSQMessagesViewController名稱頂部

screenshot of my chat

換句話說,我只是希望它在很「第一」的消息,他顯示用戶名/她發送。我試圖解決這個問題,在attributedTextForMessageBubbleTopLabelAt沒有運氣。

我試圖檢查前面的消息的senderId是否等於先前的senderId - 然後以某種方式查明它是否可以顯示或不顯示。但是,這導致了許多失敗的嘗試,包括可選錯誤,索引超出範圍,並且僅僅是不能解決問題。

這是我現在所擁有的代碼:

let message = messages[indexPath.item] 

    switch message.senderId { 

    case FIRAuth.auth()!.currentUser!.uid: 
     return nil 
     break 

    default: 

     guard let senderDisplayName = message.senderDisplayName else { 
      assertionFailure() 
      return nil 
     } 

     let paragraphStyle = NSMutableParagraphStyle() 
     paragraphStyle.alignment = NSTextAlignment.left 

     let attributedString = NSAttributedString(string: message.senderDisplayName, 
                attributes: [ 
                NSParagraphStyleAttributeName: paragraphStyle, 
                NSBaselineOffsetAttributeName: NSNumber(value: 0) 
      ]) 

     return attributedString 
     break 

    } 

回答

0

這是第一次在一個難以解決的問題時,你第一次看到它。我們需要做的是確定一條消息是否是一組消息中的第一條消息。所以我創建了一個函數來確定是否該消息是該人發送的第一個消息。

private func firstMessageInSet(indexOfMessage: IndexPath) -> Bool { 
    return messages[safe: indexOfMessage.item - 1]?.senderId() == messages[safe: indexOfMessage.item]?.senderId() 
} 

它簡單地檢查透水消息的senderId如果是一樣的當前消息。

然後,只需調用那個傢伙在這個方法:

override func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath!) -> NSAttributedString! { 
    guard let message = messages[safe: indexPath.item] else { return nil } 
    return firstMessageInSet(indexOfMessage: indexPath) ? nil : NSAttributedString(string: message.senderDisplayName) 
} 

這將檢查其是否在集合的第一個,如果它是返回senderDisplayName。現在,這是使用短手,但最終是一樣

if firstMessageInSet(indexOfMessage: indexPath) { 
    return NSAttributedString(string: message.senderDisplayName) 
} else { 
    return nil 
} 

希望這可以幫助你運氣好東西

+0

你好牛!首先,非常感謝你試圖幫助我。不幸的是,我遇到了一個奇怪的錯誤。你看,你的代碼確實有效,並沒有給我一個'索引超出範圍'的錯誤,這是我最後一次得到的。現在的問題是,這個名字沒有顯示在'第一條信息'上。它僅在第二個顯示。我試圖玩'firstMessageInSet'函數,但沒有運氣。你碰巧知道爲什麼會發生這種情況?我很親密! – askaale

+0

嘗試連續發送3封郵件。如果它在第二個和第三個消息上具有發件人顯示名稱,那麼我可能已經交換了該方法的邏輯。 –

+0

它應該是這個'return firstMessageInSet(indexOfMessage:indexPath)? NSAttributedString(string:message.senderDisplayName):nil }'不適當更新答案 –

相關問題