更改聊天气泡中的textview颜色

时间:2016-12-27 13:32:55

标签: swift swift3 jsqmessagesviewcontroller

我正在寻找一种方法来改变泡沫中的消息文本颜色,我在ObjC示例中发现它很容易,尝试在swift但是失败时做同样的事情,任何解决方案?

这是ObjC代码

- (UICollectionViewCell *)collectionView:(JSQMessagesCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    /**
     *  Override point for customizing cells
     */
    JSQMessagesCollectionViewCell *cell = (JSQMessagesCollectionViewCell *)[super collectionView:collectionView cellForItemAtIndexPath:indexPath];

    /**
     *  Configure almost *anything* on the cell
     *
     *  Text colors, label text, label colors, etc.
     *
     *
     *  DO NOT set `cell.textView.font` !
     *  Instead, you need to set `self.collectionView.collectionViewLayout.messageBubbleFont` to the font you want in `viewDidLoad`
     *
     *
     *  DO NOT manipulate cell layout information!
     *  Instead, override the properties you want on `self.collectionView.collectionViewLayout` from `viewDidLoad`
     */

    JSQMessage *msg = [self.demoData.messages objectAtIndex:indexPath.item];

    if (!msg.isMediaMessage) {

        if ([msg.senderId isEqualToString:self.senderId]) {
            cell.textView.textColor = [UIColor blackColor];
        }
        else {
            cell.textView.textColor = [UIColor whiteColor];
        }

        cell.textView.linkTextAttributes = @{ NSForegroundColorAttributeName : cell.textView.textColor,
                                              NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle | NSUnderlinePatternSolid) };
    }
    cell.accessoryButton.hidden = ![self shouldShowAccessoryButtonForMessage:msg];

    return cell;
}**

我的快速审判 Swift version

根据需要将其编辑为collectionview,然后再次崩溃

enter image description here

1 个答案:

答案 0 :(得分:4)

根据您在上面发布的Objective c代码,您需要使用JSQMessagesCollectionViewCell创建super.collectionView(_:cellForRowAt:)实例,所以请尝试这样做。

let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell

完整解决方案:

 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell

        // messages to show
        let msg = incomingMessages[indexPath.row]

        if !msg.isMediaMessage {
            if msg.senderId! == senderId {
                cell.textView.textColor = UIColor.white
            }else{
                cell.textView.textColor = UIColor.black
            }
            cell.textView.linkTextAttributes = [NSForegroundColorAttributeName: cell.textView.textColor ?? UIColor.white]
        }
        return cell 
    }