我正在使用JSQMessagesViewController进行聊天应用,我希望将每个用户名属性设置为不同的颜色
在我的createAvatar函数中,我为ColorForEachUser词典指定了不同的颜色:
var avatars = [String:JSQMessagesAvatarImage]()
var colorsForEachUser = [String: UIColor]()
func createAvatar(senderID: String, senderDisplayName:String , senderPhoneNumber : String, color:UIColor){
if avatars[senderID] == nil{
//MARK: - load the user image in avatar
let profileImageName = "\(senderPhoneNumber)_small.jpg"
let profileImagePath = fileInDocumentsDirectory(profileImageName)
if let loadedImage = loadImageFromPath(profileImagePath){
print(" Loaded Image from document directory: \(loadedImage)")
let avatar = JSQMessagesAvatarImageFactory.avatarImageWithImage(loadedImage, diameter: 70)
avatars[senderID] = avatar
}else{
print("not found in document directory")
let avatar = JSQMessagesAvatarImageFactory.avatarImageWithImage(UIImage(named:"defaultUser.png" ), diameter: 70)
avatars[senderID] = avatar
}
//MARK: - load the user color in avatar name
let colors = [TwitterBlue , pinkIlana , facebookBlue , favoritesRedColor, orange, purple , greenFluo, greenOlive ,yellowFluo, pinkFluo, redFull, brown, greenLight, blueBlack]
// POPULATING MY DICTIONNARY
colorsForEachUser[senderID] = colors[Int(arc4random_uniform(13))]
}
}
我在我的attributionTextForMessageBubbleTopLabelAtIndexPath函数中使用它:
//MARK: text top of the bubble
override func collectionView(collectionView: JSQMessagesCollectionView?, attributedTextForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
let message = messages[indexPath.item]
switch message.senderId {
case senderId:
return nil
default:
guard let senderDisplayName = message.senderDisplayName else {
assertionFailure()
return nil
}
let range = (senderDisplayName as NSString).rangeOfString(senderDisplayName)
//HERE I TRY TO USE DIFFERENT COLORS
let attributedString =
NSMutableAttributedString(string:senderDisplayName)
attributedString.addAttribute(NSForegroundColorAttributeName, value: colorsForEachUser[senderId]! , range: range)
return attributedString
}
}
但是对于不是我的用户,我获得了相同的颜色。 谢谢你的帮助!
答案 0 :(得分:1)
我的坏! 在归属
时,必须在colorsForEachUser [senderId]中将senderId更改为message.senderId