Label借助富文本顯示圖片
1.即時通訊項目中語音消息UI的實現,樣式如圖:

// 1.創建一個可變的富文本
NSMutableAttributedString *voiceAttr = [[NSMutableAttributedString alloc] init];
if ([self.reuseIdentifier isEqualToString:@"receiveCell"]) { // 接收方的label:圖片 + 時間
// 2.創建圖片富文本附件
NSTextAttachment *imageAttachment = [[NSTextAttachment alloc] init];
UIImage *voiceImage = [UIImage imageNamed:@"chat_receiver_audio_playing_full"];
// 2.1指定富文本附件的圖片
imageAttachment.image = voiceImage;
// 2.2設置圖片的frame,-7是為了圖片和文字橫向對齊一點
imageAttachment.bounds = CGRectMake(0, -7, 30, 30);
// 2.3將圖片富文本附件添加到富文本中
NSAttributedString *imgAttr = [NSAttributedString attributedStringWithAttachment:imageAttachment];
// 3.將圖片富文本添加到可變的富文本中
[voiceAttr appendAttributedString:imgAttr];
// 4.創建時間文字的富文本
EMVoiceMessageBody *voiceBody = [message.messageBodies firstObject];
NSInteger time = voiceBody.duration;
NSAttributedString *timeAtt = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@" %ld″",time]];
[voiceAttr appendAttributedString:timeAtt];
} else { // 發送方的label: 時間 + 圖片
// 4.創建時間文字的富文本
EMVoiceMessageBody *voiceBody = [message.messageBodies firstObject];
NSInteger time = voiceBody.duration;
NSAttributedString *timeAtt = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%ld″ ",time]];
[voiceAttr appendAttributedString:timeAtt];
// 2.創建圖片富文本
NSTextAttachment *imageAttachment = [[NSTextAttachment alloc] init];
UIImage *voiceImage = [UIImage imageNamed:@"chat_sender_audio_playing_full"];
imageAttachment.image = voiceImage;
imageAttachment.bounds = CGRectMake(self.msgLabel.bounds.size.width - 30, -7, 30, 30);
NSAttributedString *imgAttr = [NSAttributedString attributedStringWithAttachment:imageAttachment];
// 3.將圖片富文本添加到可變的富文本中
[voiceAttr appendAttributedString:imgAttr];
}
2.即時通訊發送圖片 -- 在UILabel中添加了UIImageView,雖然設置了UILabel的尺寸,但是並沒有什么卵用.UILabel尺寸沒變,圖片也顯示的不全


- 使用富文本當做占位符的作用,先將UILabel撐到顯示圖片的大小
- 最后將UIImageView添加到UILabel中問題就解決了
EMImageMessageBody *imageBody = [self.message.messageBodies firstObject];
// 1.給label設置富文本,目的:占位,將label撐大,足夠顯示縮略圖
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.bounds = (CGRect){0, 0, imageBody.thumbnailSize};
// 2.給label添加富文本
self.msgLabel.attributedText = [NSAttributedString attributedStringWithAttachment:attachment];
// 3.將UIImageView添加到UILabel中
[self.msgLabel addSubview:self.msgImageView];
NSString *path;
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:[imageBody thumbnailLocalPath]]) { // 本地有圖片的情況
path = imageBody.thumbnailLocalPath;
[self.msgImageView sd_setImageWithURL:[NSURL fileURLWithPath:path] placeholderImage:nil];
} else { // 本地沒有圖片的情況
path = imageBody.thumbnailRemotePath;
[self.msgImageView sd_setImageWithURL:[NSURL URLWithString:path] placeholderImage:nil];
}
// 4.設置圖片的位置與尺寸
self.msgImageView.frame = (CGRect){0, 0, imageBody.thumbnailSize};