【问题标题】:create a simple chat view in ios在 ios 中创建一个简单的聊天视图
【发布时间】: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


【解决方案1】:

例如,您需要创建多个具有不同 CellIdentifier 的单元格。单元格用于发送者和接收者。您可以将其细分为文本、音频、视频、图像等类别。

here下载示例 ChatUI Demo(Objective-C 和 Swift)

让我们举个文字聊天的例子。

首先,您需要在 Storyboard 或 XIB 中使用不同的 CellIdentifier 创建 2 个单元原型,例如“cellSender”和“cellReceiver”。

UILabelUITextView 放在单元格内,cellSender 左对齐,cellReceiver 右对齐,以便为发送者和接收者制作不同的布局。

然后你可以用你的代码来做...

  - (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BOOL sender = NO;

// Check for the sender or receiver 
    <code for checking message is from sender or receiver>

    static NSString *CellIdentifier = sender?@"cellSender":@"cellReceiver";

    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 = NSTextAlignmentLeft;
    messageLabel.textColor = [UIColor darkTextColor];
    messageLabel.backgroundColor = sender? [UIColor greenColor]: [UIColor lightGrayColor];
    messageLabel.numberOfLines = 0;
    messageLabel.layer.cornerRadius = 8;
    messageLabel.layer.masksToBounds = YES;

    messageLabel.text = [listOfMessages objectAtIndex:indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    return cell;
    }

编辑

【讨论】:

  • 如何创建 2 个单元原型。因为我没有使用 StoryBoard 或 Xibs
  • 嗨壁画,我已经能够在两个不同的 nib 文件上使用两个自定义单元来实现这一点。如何设置标签框,使其与文字大小相等。
  • @mrunal 谢谢....请提供上述解释的示例代码...我也需要相同的功能
  • 嗨@Priya,您可以从我上面的编辑中找到简单聊天 UI 的演示。
  • @mrunalthanki...请在 Objective-C 中更新。提前致谢
【解决方案2】:

您可以使用两个不同的自定义单元格,一个用于发送者,一个用于接收者,如下所示:

  1. 发件人

  1. 对于接收方

现在,在您的应用中,必须有登录和注册过程,因为它是一个聊天应用,并且会有与您的应用关联的服务器来保存数据。

你可以做的是,当你发送消息时,也发送接收者的名字并将它存储在你的数据库中。

现在,在您的聊天视图中,获取所有消息数据以及接收者姓名。

在登录过程中获取当前登录的userName

您可以在 cellForRowAtIndexPath: 中执行类似操作

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSString *myArrayElement = [arr_receiverUserName objectAtIndex:indexPath.row];

    //do something useful with myArrayElement

    if(![myArrayElement isEqualToString:userName])
    {
         /// These are my messages.
         //// Pop up 'mycell' here 

            UILabel *lbl_myText = [[UILabel alloc]initWithFrame:CGRectZero];
            [lbl_myText setLineBreakMode:NSLineBreakByWordWrapping];
            lbl_myText.minimumScaleFactor = FONT_SIZE;
            [lbl_myText setNumberOfLines:0];
            lbl_myText.textAlignment = NSTextAlignmentRight;
            [lbl_myText setFont:[UIFont systemFontOfSize:FONT_SIZE]];

            NSString *text = [arr_text objectAtIndex:indexPath.row];

            CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]];

            // Checks if text is multi-line
            if (size.width > lbl_myText.bounds.size.width)
            {
                CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

                CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

                [lbl_myText setText:text];
                [lbl_myText setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - cell.imgv_myImage.frame.size.width -(CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
            }

            else
            {
                lbl_myText.frame = CGRectMake(10, 0, cell.frame.size.width - cell.imgv_myImage.frame.size.width - 18,18);
                lbl_myText.textAlignment = NSTextAlignmentRight;
                [lbl_myText setText:text];
            }

            //lbl_myText.backgroundColor = [UIColor greenColor];

            [cell.contentView addSubview:lbl_myText];

    }

    else
    {
        //// These are the messages sent by some one else

       /// Pop up `someonecell` here

        UILabel *lbl_myText = [[UILabel alloc]initWithFrame:CGRectZero];
        [lbl_myText setLineBreakMode:NSLineBreakByWordWrapping];
        lbl_myText.minimumScaleFactor = FONT_SIZE;
        [lbl_myText setNumberOfLines:0];
        lbl_myText.textAlignment = NSTextAlignmentLeft;
        [lbl_myText setFont:[UIFont systemFontOfSize:FONT_SIZE]];

        NSString *text = [arr_text objectAtIndex:indexPath.row];

        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]];

        // Checks if text is multi-line
        if (size.width > lbl_myText.bounds.size.width)
        {
            CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

            CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

            [lbl_myText setText:text];
            [lbl_myText setFrame:CGRectMake(cell.imgv_someoneImage.frame.size.width+8, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - cell.imgv_someoneImage.frame.size.width -(CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
        }

        else
        {
            lbl_myText.frame = CGRectMake(10, 0, cell.frame.size.width - cell.imgv_someoneImage.frame.size.width - 18,18);
            lbl_myText.textAlignment = NSTextAlignmentLeft;
            [lbl_myText setText:text];
        }

        //lbl_myText.backgroundColor = [UIColor greenColor];

        [cell.contentView addSubview:lbl_myText];

    }

你可以对图像和音频做类似的事情。


对于单元格的动态高度:

要根据您的UILabels调整单元格的高度,请参考Increase the main tableview row height according to the custom cell

【讨论】:

  • 我没有使用nibs或者storyboard,能不能通过代码告诉我如何实现
  • 我已经更新了答案...但是为什么要让自己为难...如果您可以使用笔尖或情节提要来做到这一点?
  • 我从未使用过 nib 文件。所以,我在问.. 但我会尝试使用 nibs alos
  • 我已经在答案中添加了这两件事。两者都需要。
  • 好的,,我会试试n回来...谢谢Rumin
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 2012-05-06
相关资源
最近更新 更多