ライブラリをインストール

ViewControllerをカスタマイズ

ViewController.swift

importUIKitimportJSQMessagesViewControllerclassViewController:JSQMessagesViewController{varmessages:[JSQMessage]?varincomingBubble:JSQMessagesBubbleImage!varoutgoingBubble:JSQMessagesBubbleImage!varincomingAvatar:JSQMessagesAvatarImage!varoutgoingAvatar:JSQMessagesAvatarImage!overridefuncviewDidLoad(){super.viewDidLoad()//自分のsenderId, senderDisokayNameを設定self.senderId="user1"self.senderDisplayName="hoge"//吹き出しの設定letbubbleFactory=JSQMessagesBubbleImageFactory()self.incomingBubble=bubbleFactory.incomingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleLightGrayColor())self.outgoingBubble=bubbleFactory.outgoingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleGreenColor())//アバターの設定self.incomingAvatar=JSQMessagesAvatarImageFactory.avatarImageWithImage(UIImage(named:"hinako")!,diameter:64)self.outgoingAvatar=JSQMessagesAvatarImageFactory.avatarImageWithImage(UIImage(named:"keita")!,diameter:64)//メッセージデータの配列を初期化self.messages=[]}overridefuncdidReceiveMemoryWarning(){super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}//Sendボタンが押された時に呼ばれるoverridefuncdidPressSendButton(button:UIButton!,withMessageTexttext:String!,senderId:String!,senderDisplayName:String!,date:NSDate!){//新しいメッセージデータを追加するletmessage=JSQMessage(senderId:senderId,displayName:senderDisplayName,text:text)self.messages?.append(message)//メッセジの送信処理を完了する(画面上にメッセージが表示される)self.finishReceivingMessageAnimated(true)//擬似的に自動でメッセージを受信self.receiveAutoMessage()}//アイテムごとに参照するメッセージデータを返すoverridefunccollectionView(collectionView:JSQMessagesCollectionView!,messageDataForItemAtIndexPathindexPath:NSIndexPath!)->JSQMessageData!{returnself.messages?[indexPath.item]}//アイテムごとのMessageBubble(背景)を返すoverridefunccollectionView(collectionView:JSQMessagesCollectionView!,messageBubbleImageDataForItemAtIndexPathindexPath:NSIndexPath!)->JSQMessageBubbleImageDataSource!{letmessage=self.messages?[indexPath.item]ifmessage?.senderId==self.senderId{returnself.outgoingBubble}returnself.incomingBubble}//アイテムごとにアバター画像を返すoverridefunccollectionView(collectionView:JSQMessagesCollectionView!,avatarImageDataForItemAtIndexPathindexPath:NSIndexPath!)->JSQMessageAvatarImageDataSource!{letmessage=self.messages?[indexPath.item]ifmessage?.senderId==self.senderId{returnself.outgoingAvatar}returnself.incomingAvatar}//アイテムの総数を返すoverridefunccollectionView(collectionView:UICollectionView,numberOfItemsInSectionsection:Int)->Int{return(self.messages?.count)!}//返信メッセージを受信するfuncreceiveAutoMessage(){NSTimer.scheduledTimerWithTimeInterval(1,target:self,selector:"didFinishMessageTimer:",userInfo:nil,repeats:false)}funcdidFinishMessageTimer(sender:NSTimer){letmessage=JSQMessage(senderId:"user2",displayName:"underscore",text:"Hello!")self.messages?.append(message)self.finishReceivingMessageAnimated(true)}}