【发布时间】:2016-01-04 05:43:55
【问题描述】:
我需要创建一个简单的聊天视图,我可以在其中显示来自两端(发送者和接收者)的消息,就像任何消息应用程序一样。
到目前为止,我所做的是,创建了一个UITableView、一个UIButton 和一个UITextField。在那个 UIButton 点击上,我将 UITextField 文本添加到数组中,现在我需要第二端,就像我们的消息应用程序(发送方)一样。
左边是接收者,右边是发送者。
到目前为止,我的应用看起来像
这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
messageLabel = nil;
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
messageLabel = [[UILabel alloc] init];
messageLabel.tag = 101;
[cell.contentView addSubview: messageLabel];
} else {
messageLabel = (UILabel*)[cell.contentView viewWithTag: 101];
} //---calculate the height for the label---
int labelHeight = [self labelHeight:[listOfMessages objectAtIndex:indexPath.row]];
labelHeight -= bubbleFragment_height;
if (labelHeight<0) labelHeight = 0;
messageLabel.frame =
CGRectMake(bubble_x + 10, bubble_y + 5,
(bubbleFragment_width * 3) - 25,
(bubbleFragment_height * 2) + labelHeight - 10);
messageLabel.font = [UIFont systemFontOfSize:15];
messageLabel.textAlignment = NSTextAlignmentCenter;
messageLabel.textColor = [UIColor darkTextColor];
messageLabel.backgroundColor = [UIColor greenColor];
messageLabel.numberOfLines = 0;
messageLabel.layer.cornerRadius = 8;
messageLabel.layer.masksToBounds = YES;
messageLabel.text = [listOfMessages objectAtIndex:indexPath.row];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
-(void) sendAction:(id) sender {
[listOfMessages addObject:field.text];
[chatTable reloadData];
field.text = @"";
[field resignFirstResponder];
}
【问题讨论】:
-
您必须创建两个自定义单元格,并将两个数组一个用于发送者,第二个用于接收者,并且两个单元格具有不同的单元格标识符,因为 mrunal 和 rubin 说您的问题会解决
-
它非常容易为单元格创建 Nib,否则您必须维护单个
UITableViewCell,它会有点复杂。所以这是所有开发者对开发者的建议。 -
不能用代码创建吗? ? @杰
-
你可以创建,但对你来说有点复杂,而且从我这边解释每个步骤也很复杂
-
好吧,如何使用 Nib 文件,
标签: ios objective-c iphone uitableview chat