2016-09-06 83 views
2

我正在嘗試創建一個聊天應用程序,並且正在使用JSQMessagesViewController庫。 我的聊天視圖顯示與他們的日期和時間的所有消息,但我正面臨着這個庫的一些小問題。 我的問題是我想只顯示消息日期一次。 假設: 昨天日期包含10個信息 今天日期包含15個信息如何在JSQMessagesViewController中顯示消息日期

,我想告訴這些消息只有一個日期不重複日期爲每一個消息enter image description here

回答

3

那麼你需要確定消息是否是當天的第一個。然後返回所有其他人爲零,直到新的一天。

我創建了一個函數來確定我的消息是第一個由人發出的。它看起來像這樣

func firstMessageOfTheDay(indexOfMessage: NSIndexPath) -> Bool { 
    let messageDate = messages[indexOfMessage.item].date 
    guard let previouseMessageDate = messages[indexOfMessage.item - 1].date else { 
    return true // because there is no previous message so we need to show the date 
    } 
    let day = Calendar.current.component(.day, from: messageDate) 
    let previouseDay = Calendar.current.component(.day, from: previouseMessageDate) 
    if day == previouseDay { 
     return false 
    } else { 
     return true 
    } 
} 

然後在相應的函數中調用它。希望有助於讓我知道你是否有其他問題。

+0

感謝丹尼爾其真正完美的答案,我需要 –

+0

我很高興它幫助 –

+0

嗨Umesh製作,你可以發表你的整個代碼用於顯示日期嗎?我找不到像你這樣的方式 –

1

使用此方法來做到這一點。

func collectionView(collectionView: JSQMessagesCollectionView, attributedTextForCellTopLabelAtIndexPath indexPath: NSIndexPath) -> NSAttributedString? { 

你必須檢查消息的日期,如果日期是不同的以哪種方式你想要否則返回零則上一條消息的日期返回日期。