我正在制作一个聊天应用程序。当消息到达时,它必须说明是谁发送的。例如,如果我是发件人,那么它应该说
武士:留言
安德烈斯:留言
我希望“Takeshi”和“Andres”的颜色不同,但与消息在同一行,换行,如下所示:
Takeshi: some message text, text, text , text
text, text, text end.
我正在尝试以下操作:
- 计算消息的大小。
- 计算发件人姓名的大小。
- 使用发件人姓名的长度创建字符串“”。
但是“”不是还不够。
我做这个:
NSString *from;
if(usr){
from = [NSString stringWithFormat:@"%@: ", @"Yo"];
}else{
from = [NSString stringWithFormat:@"%@: ", [_lbSupportName text]];
}
//This give me one string of n characters of ' ' character.
NSString *spaces = [ChatView stringWithRepeatCharacter:' ' times:from.length * 2];
NSString *mensaje = [NSString stringWithFormat:@"%@ %@", spaces, msg];
//Calculating the height
CGSize messageSize = [mensaje sizeWithFont:[UIFont fontWithName:DEFAULT_TEXTFONT size:20]
constrainedToSize:CGSizeMake(_scvConversation.frame.size.width - 10, FLT_MAX)
lineBreakMode:UILineBreakModeWordWrap];
CGSize fromSize = [from sizeWithFont:[UIFont fontWithName:DEFAULT_TEXTFONT size:22]
constrainedToSize:CGSizeMake(FLT_MAX, FLT_MAX)
lineBreakMode:UILineBreakModeWordWrap];
//Image Background
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(5, yConversationPosition + 5, _scvConversation.frame.size.width - 10, messageSize.height + 30)];
yConversationPosition += image.frame.size.height + 5;
//Create the Label From
UILabel *lb_From = [[UILabel alloc] initWithFrame:CGRectMake(0, 9, fromSize.width, 30)];
[lb_From setFont:[UIFont fontWithName:DEFAULT_TEXTFONT size:20]];
[lb_From setBackgroundColor:[UIColor clearColor]];
[lb_From setText:from];
//Create the Label Message
UILabel *lb_WriteMessage = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, image.frame.size.width-10, image.frame.size.height - 10)];
[lb_WriteMessage setNumberOfLines:messageSize.height / DEFAULT_TEXTSIZE];
[lb_WriteMessage setFont:[UIFont fontWithName:DEFAULT_TEXTFONT size:20]];
[lb_WriteMessage setText:mensaje];
[lb_WriteMessage setBackgroundColor:[UIColor clearColor]];
[lb_WriteMessage setTextColor:[UIColor colorWithRed:(92/255.0f) green:(98/255.0f) blue:(101/255.0f) alpha:1]];
if(usr){
[image setImage:[UIImage imageNamed:@"chat-mensajes-yo.png"]];
[lb_From setTextColor:[UIColor colorWithRed:(230/255.0f) green:(85/255.0f) blue:(84/255.0f) alpha:1]];
}else{
[image setImage:[UIImage imageNamed:@"chat-mensajes-asesor.png"]];
[lb_From setTextColor:[UIColor colorWithRed:(28/255.0f) green:(168/255.0f) blue:(175/255.0f) alpha:1]];
}
[lb_WriteMessage addSubview:lb_From];
[image addSubview:lb_WriteMessage];
[_scvConversation addSubview:image];
//Set the contentSize of the scv_Message and scroll to the new Message
[_scvConversation setContentSize:CGSizeMake(0, yConversationPosition)];
if(_scvConversation.contentSize.height > _scvConversation.frame.size.height){
//Scroll to last Message
float diference = yConversationPosition - _scvConversation.frame.size.height +5;
[_scvConversation setContentOffset:CGPointMake(0, diference)];
}
[image release];
[lb_WriteMessage release];
请帮忙,我做不到。:/