欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS实现搭建聊天页面的实例代码

程序员文章站 2023-12-21 13:11:52
由于工作需要,需要用到ios聊天页面,在网上搜了半天没有想要的,果断自己写一个,发个笔记 功能分析,模仿qq聊天页面 输入框失去第一响应的情况: 1:点击页面...

由于工作需要,需要用到ios聊天页面,在网上搜了半天没有想要的,果断自己写一个,发个笔记

功能分析,模仿qq聊天页面

输入框失去第一响应的情况:

1:点击页面

2:下滑页面

输入框成为第一响应的情况:

1:开始输入

2:上滑页面最底部

iOS实现搭建聊天页面的实例代码

控制器

//
// wdpersonmessagedetailvc.m
// westdevelopment
//
// created by wangtao on 2017/6/23.
// copyright © 2017年 xikaijinfu. all rights reserved.
//

#import "wdpersonmessagedetailvc.h"
#import "wdpersonmessagedetailcell.h"
#import "wdpersonmessagefootercell.h"
#import "wdpersonmessagedetailmodel.h"

#import <iqkeyboardmanager.h>

@interface wdpersonmessagedetailvc ()

@property (nonatomic, weak) wdpersonmessagefootercell *textfieldview;

@end

@implementation wdpersonmessagedetailvc

- (void)scrollviewdidscroll:(uiscrollview *)scrollview
{
  cgfloat contentoffsety = scrollview.contentoffset.y;

//  页面下滑,并且输入框还是第一响应的时候,控制器要失去第一响应
  if (contentoffsety > 10) {
    if (self.textfieldview.isfirst) {
      [self clickself];
    }
  }

  //  页面上滑,控制器成为第一响应
  if (contentoffsety < - 10) {
    self.textfieldview.isfirst = yes;
  }
}

- (void)viewdidappear:(bool)animated
{
  [super viewdidappear:animated];

//  关闭iq键盘
  [iqkeyboardmanager sharedmanager].enable = no;
  [iqkeyboardmanager sharedmanager].enableautotoolbar = no;
}

- (void)viewwilldisappear:(bool)animated
{
  [super viewwilldisappear:animated];
  [self.view endediting:yes];
}

- (void)viewdiddisappear:(bool)animated
{
  [super viewdiddisappear:animated];

  [iqkeyboardmanager sharedmanager].enableautotoolbar = yes;
  [iqkeyboardmanager sharedmanager].enable = yes;
}

- (void)dealloc
{
  [[nsnotificationcenter defaultcenter] removeobserver:self];
}

- (void)loadview
{
  uiscrollview *view = [[uiscrollview alloc] init];
  view.frame = cgrectmake(0, 0, kmainscreenwidth, kmainscreenheight);
  self.view = view;

}

- (void)viewdidload {
  [super viewdidload];
  // do any additional setup after loading the view.

  [iqkeyboardmanager sharedmanager].enable = no;
  [iqkeyboardmanager sharedmanager].enableautotoolbar = no;

  [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(keyboardwillshow:) name:uikeyboardwillshownotification object:nil];
  [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(keyboardwillhide:) name:uikeyboardwillhidenotification object:nil];

//  旋转tableview
  self.tableview.transform = cgaffinetransformmakescale (1, -1);
  self.tableview.tableheaderview.transform = cgaffinetransformmakescale (1, -1);
  self.tableview.tablefooterview.transform = cgaffinetransformmakescale (1, -1);

  self.view.backgroundcolor = wthexcolor(0xeaeaea);
  self.tableview.backgroundcolor = wthexcolor(0xeaeaea);
  self.tableview.scrollindicatorinsets = uiedgeinsetsmake(50, 0, 0, 0);

  [self.tableview registerclass:[wdpersonmessagedetailcell class] forcellreuseidentifier:wdpersonmessagedetailcellid];
  [self.tableview registerclass:[wdpersonmessagefootercell class] forheaderfooterviewreuseidentifier:wdpersonmessagefootercellid];

  [self.tableview wt_addtaptarget:self action:@selector(clickself)];

  [self addfooter];

}
//键盘弹出时把消息列表tableview的高度设为(屏幕高度 - 输入框高度 - 键盘高度),同时输入框上移;
//键盘消失时再把tableview的高度设为(屏幕高度 - 输入框的高度),同时输入框下移。
//这样可以完美解决聊天列表的上面的消息无法显示问题和键盘遮挡问题。
- (void)keyboardwillshow:(nsnotification*)notification
{
  // 0.取出键盘动画的时间
  cgfloat duration = [notification.userinfo[uikeyboardanimationdurationuserinfokey] doublevalue];
  // 1.取得键盘最后的frame
  cgrect keyboardframe = [notification.userinfo[uikeyboardframeenduserinfokey] cgrectvalue];
  // 2.计算控制器的view需要平移的距离
  cgfloat transformy = keyboardframe.origin.y - self.view.frame.size.height;

  // 3.执行动画
  nsindexpath *indexpath = [nsindexpath indexpathforrow:0 insection:0];
  [self.tableview scrolltorowatindexpath:indexpath atscrollposition:uitableviewscrollpositionbottom animated:no];

  wtws(weakself);
  dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(.05 * nsec_per_sec)), dispatch_get_main_queue(), ^{

    [uiview animatewithduration:duration animations:^{
      weakself.tableview.frame = cgrectmake(0, 0, kmainscreenwidth, kmainscreenheight - keyboardframe.size.height - 64);
      weakself.inputview.transform = cgaffinetransformmaketranslation(0, transformy);

    }];
  });

}

- (void)keyboardwillhide:(nsnotification*)notification
{
  cgfloat duration = [notification.userinfo[uikeyboardanimationdurationuserinfokey] doublevalue];
  [uiview animatewithduration:duration animations:^{
    self.tableview.frame = cgrectmake(0, 0, kmainscreenwidth, kmainscreenheight);
    self.view.transform = cgaffinetransformidentity;

  }];

}

//失去第一响应
- (void)clickself
{
  [[nsnotificationcenter defaultcenter] postnotificationname:kmessagestate object:@(yes)];
}

- (void)addheader
{
  __unsafe_unretained __typeof(self) weakself = self;
  self.tableview.mj_header = [mjrefreshnormalheader headerwithrefreshingblock:^{
    [weakself loaddata];
  }];

  [self.tableview.mj_header beginrefreshing];
}

//关闭下拉和上拉控件的文字展示
- (void)addfooter
{
//  [self addheader];
  [self loaddata];

  mjrefreshautonormalfooter *footer = [mjrefreshautonormalfooter footerwithrefreshingtarget:self refreshingaction:@selector(loadmoredata)];

  [footer settitle:@"" forstate:mjrefreshstateidle];
  [footer settitle:@"" forstate:mjrefreshstatepulling];
  [footer settitle:@"" forstate:mjrefreshstaterefreshing];
  [footer settitle:@"" forstate:mjrefreshstatewillrefresh];
  [footer settitle:@"" forstate:mjrefreshstatenomoredata];

  self.tableview.mj_footer = footer;

}

- (void)loaddata
{
  self.page = 1;

  nsdictionary *par = @{
             ktoken :     [wtaccount shareaccount].token,
             kuserid :     [wtaccount shareaccount].uid,
             kcurrentpage :  @(self.page),
             kfriendid :    self.friendid,
             };

  [wdnetwork postkmymessagedetailphonewithparameters:par modelclass:[wdpersonmessagedetailmodel class] responseblock:^(id dataobject, nserror *error) {
    if (!error && [[dataobject class] issubclassofclass:[nsarray class]]) {
      nsarray* reversedarray = [[dataobject reverseobjectenumerator] allobjects];
      self.dataarray = [nsmutablearray arraywitharray:reversedarray];
      [self.tableview reloaddata];
      self.page ++;
      if ([dataobject count] < 20) {
        [self.tableview.mj_header endrefreshing];
        [self.tableview.mj_footer endrefreshingwithnomoredata];
      } else {
        [self.tableview.mj_header endrefreshing];
        [self.tableview.mj_footer endrefreshing];
      }
    } else {
      [self.tableview.mj_header endrefreshing];
      [self.tableview.mj_footer endrefreshingwithnomoredata];
    }
  }];
}

- (void)loadmoredata
{
  nsdictionary *par = @{
             ktoken :     [wtaccount shareaccount].token,
             kuserid :     [wtaccount shareaccount].uid,
             kcurrentpage :  @(self.page),
             kfriendid :    self.friendid,
             };

  [wdnetwork postkmymessagedetailphonewithparameters:par modelclass:[wdpersonmessagedetailmodel class] responseblock:^(id dataobject, nserror *error) {
    if (!error && [[dataobject class] issubclassofclass:[nsarray class]]) {
      nsarray* reversedarray = [[dataobject reverseobjectenumerator] allobjects];
      [self.dataarray addobjectsfromarray:reversedarray];
      [self.tableview reloaddata];
      self.page ++;
      if ([dataobject count] < 20) {
        [self.tableview.mj_footer endrefreshingwithnomoredata];
      } else {
        [self.tableview.mj_footer endrefreshing];
      }
    } else {
      [self.tableview.mj_footer endrefreshingwithnomoredata];
    }
  }];
}

- (cgfloat)tableview:(uitableview *)tableview heightforheaderinsection:(nsinteger)section
{
  return 50;
}

- (cgfloat)tableview:(uitableview *)tableview heightforfooterinsection:(nsinteger)section
{
  return cgfloat_min;
}

- (uiview *)tableview:(uitableview *)tableview viewforheaderinsection:(nsinteger)section
{
  wdpersonmessagefootercell *footer = [tableview dequeuereusableheaderfooterviewwithidentifier:wdpersonmessagefootercellid];
  self.textfieldview = footer;
  footer.contentview.transform = cgaffinetransformmakescale (1, -1);

  wtws(weakself);
  footer.clicksendertext = ^(nsstring *text) {
    nsdictionary *par = @{
               ktoken :     [wtaccount shareaccount].token,
               kuserid :     [wtaccount shareaccount].uid,
               kcomment :    text,
               kflag :      @(11),
               kfriendid :    weakself.friendid,
               };
    [wdnetwork postkaddcommentphonewithparameters:par modelclass:[nsnull class] responseblock:^(id dataobject, nserror *error) {
      if (!error && ([[dataobject objectforkey:kcode] integervalue] == 200)) {
        [weakself loaddata];
        weakself.textfieldview.sendsucceed = yes;
      } else if (!error && [dataobject objectforkey:kmsg]) {
      }
    }];
  };

  footer.resignfirstres = ^{
    weakself.tableview.frame = cgrectmake(0, 0, kmainscreenwidth, kmainscreenheight - 64);
    weakself.view.transform = cgaffinetransformidentity;
  };
  return footer;
}

- (nsinteger)numberofsectionsintableview:(uitableview *)tableview
{
  return 1;
}

- (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section
{
  return self.dataarray.count;
}

- (cgfloat)tableview:(uitableview *)tableview heightforrowatindexpath:(nsindexpath *)indexpath
{
  wdpersonmessagedetailmodel *model = self.dataarray[indexpath.row];
  return model.height;
}

- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath
{
  wdpersonmessagedetailcell *cell = [tableview dequeuereusablecellwithidentifier:wdpersonmessagedetailcellid forindexpath:indexpath];
  cell.model = self.dataarray[indexpath.row];
  cell.contentview.transform = cgaffinetransformmakescale (1, -1);
  return cell;
}


- (void)didreceivememorywarning {
  [super didreceivememorywarning];
  // dispose of any resources that can be recreated.
}

/*
#pragma mark - navigation

// in a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender {
  // get the new view controller using [segue destinationviewcontroller].
  // pass the selected object to the new view controller.
}
*/

@end

输入框 uitableviewheaderfooterview

//
// wdpersonmessagefootercell.h
// westdevelopment
//
// created by wangtao on 2017/6/26.
// copyright © 2017年 xikaijinfu. all rights reserved.
//

#import "wdbasetvheaderfooterview.h"

typedef void(^clicksender_t)(nsstring *text);

typedef void(^resignfirstresponder)();

@interface wdpersonmessagefootercell : wdbasetvheaderfooterview

@property (nonatomic, copy) clicksender_t clicksendertext;
@property (nonatomic, copy) resignfirstresponder resignfirstres;

@property (nonatomic, assign) bool isfirst;
@property (nonatomic, assign) bool sendsucceed;

@end

//
// wdpersonmessagefootercell.m
// westdevelopment
//
// created by wangtao on 2017/6/26.
// copyright © 2017年 xikaijinfu. all rights reserved.
//

#import "wdpersonmessagefootercell.h"


@interface wdpersonmessagefootercell () <uitextfielddelegate>

@property (nonatomic, weak) uitextfield *textfield;
@property (nonatomic, weak) uiview *line;

@end


@implementation wdpersonmessagefootercell

@synthesize isfirst = _isfirst;

- (void)setupall
{
  self.contentview.backgroundcolor = wthexcolor(0xf2f2f2);

  uitextfield *textfield = [[uitextfield alloc] init];
  textfield.backgroundcolor = kwhitecolor;
  [self.contentview addsubview:textfield];
  textfield.delegate = self;
  self.textfield = textfield;
  textfield.layer.cornerradius = 3;
  textfield.layer.maskstobounds = yes;

  textfield.returnkeytype = uireturnkeysend;

  [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(messagestate:) name:kmessagestate object:nil];

  uiview *line = [[uiview alloc] init];
  line.backgroundcolor = wthexcolor(0xdddddd);
  [self.contentview addsubview:line];
  self.line = line;

}

- (void)messagestate:(nsnotification *)noti
{
  nsinteger state = [[noti object] boolvalue];
  if (state) {
    [self.textfield resignfirstresponder];
    if (self.resignfirstres) {
      self.resignfirstres();
    }
  }
}

- (bool)textfieldshouldreturn:(uitextfield *)textfield
{
  if (self.clicksendertext) {
    self.clicksendertext(self.textfield.text);
  }
  return yes;
}

- (void)setisfirst:(bool)isfirst
{
  _isfirst = isfirst;
  if (isfirst) {
    [self.textfield becomefirstresponder];
  } else {
    [self.textfield resignfirstresponder];
  }
}

- (bool)isfirst
{
  if ([self.textfield isfirstresponder]) {
    return yes;
  }
  return no;
}

- (void)setsendsucceed:(bool)sendsucceed
{
  self.textfield.text = @"";
}

- (void)layoutsubviews
{
  [super layoutsubviews];

  cgfloat padding = 10;
  self.textfield.frame = cgrectmake(padding, padding, self.wt_width - padding * 2, self.wt_height - padding * 2);
  self.line.frame = cgrectmake(0, 0, self.wt_width, .5);
}

@end

消息cell

//
// wdpersonmessagedetailcell.m
// westdevelopment
//
// created by wangtao on 2017/6/23.
// copyright © 2017年 xikaijinfu. all rights reserved.
//

#import "wdpersonmessagedetailcell.h"
#import "wdpersonmessagedetailmodel.h"


@interface wdpersonmessagedetailcell ()

@property (nonatomic, weak) uilabel *time;
@property (nonatomic, weak) uiimageview *icon;
@property (nonatomic, weak) uilabel *detail;

@property (nonatomic, weak) uiview *baseview;

@end

@implementation wdpersonmessagedetailcell

- (void)setupall
{
  self.selectionstyle = uitableviewcellselectionstylenone;

  self.backgroundcolor = wthexcolor(0xeaeaea);
  self.contentview.backgroundcolor = wthexcolor(0xeaeaea);

  uilabel *time = [uilabel labelwithtext:@""
                 textcolor:wthexcolor(0xaaaaaa)
               textalignment:nstextalignmentcenter
                   font:12
              backgroundcolor:kclearcolor];
  [self.contentview addsubview:time];
  self.time = time;

  uiimageview *icon = [[uiimageview alloc] init];
  [self.contentview addsubview:icon];
  icon.image = [uiimage imagenamed:kdefault];
  self.icon = icon;
  self.icon.layer.cornerradius = 35 / 2;
  self.icon.layer.maskstobounds = yes;

  uiview *baseview = [[uiview alloc] init];
  [self.contentview addsubview:baseview];
  self.baseview = baseview;
  baseview.layer.maskstobounds = yes;
  baseview.layer.cornerradius = 4;

  uilabel *detail = [uilabel labelwithtext:@""
                  textcolor:kblackcolor
                textalignment:nstextalignmentleft
                    font:13
               backgroundcolor:kclearcolor];
  [baseview addsubview:detail];
  self.detail = detail;
  detail.numberoflines = 0;

}

- (void)setmodel:(wdpersonmessagedetailmodel *)model
{
  _model = model;

  if ([model.isshow isequaltostring:@"1"]) {
    self.time.text = model.addtime;
    self.time.hidden = no;
    self.time.frame = cgrectmake(0, 0, kmainscreenwidth, 20);

  } else {
    self.time.text = @"";
    self.time.hidden = yes;
    self.time.frame = cgrectzero;

  }

  self.time.text = model.addtime;
  [self.icon wt_setimagewithurlstring:model.headimg placeholderstring:@"me_icon"];
  self.detail.text = model.comment;

  if ([model.userid isequaltostring:[wtaccount shareaccount].uid]) {
    self.detail.textcolor = kblackcolor;
    self.baseview.backgroundcolor = kwhitecolor;

    self.icon.frame = cgrectmake(kpadding, self.time.wt_bottom + kpadding, 35, 35);
    self.baseview.frame = cgrectmake(self.icon.wt_right + kpadding, self.icon.wt_top, model.commentw, model.commenth);
    self.detail.frame = cgrectmake(kpadding, kpadding, model.commentw - kpadding * 2, model.commenth - kpadding * 2);

  } else {
    self.detail.textcolor = kwhitecolor;
    self.baseview.backgroundcolor = khomecolor;

    self.icon.frame = cgrectmake(kmainscreenwidth - 35 - kpadding, self.time.wt_bottom + kpadding, 35, 35);
    self.baseview.frame = cgrectmake(self.icon.wt_left - kpadding - model.commentw, self.icon.wt_top, model.commentw, model.commenth);
    self.detail.frame = cgrectmake(kpadding, kpadding, model.commentw - kpadding * 2, model.commenth - kpadding * 2);

  }

}


@end

模型

//
// wdpersonmessagedetailmodel.m
// westdevelopment
//
// created by wangtao on 2017/6/23.
// copyright © 2017年 xikaijinfu. all rights reserved.
//

#import "wdpersonmessagedetailmodel.h"

@implementation wdpersonmessagedetailmodel

- (cgfloat)commentw
{
  if (_commentw == 0) {
    _commentw = [self.comment wt_calculatestringsizewithfontofsize:13 maxwidth:kmainscreenwidth / 2].width + 20;
  }
  return _commentw;
}

- (cgfloat)commenth
{
  if (_commenth == 0) {
    cgfloat texth = [self.comment wt_calculatestringsizewithfontofsize:13 maxwidth:kmainscreenwidth / 2].height;
    // 一行字体是15高,一行的情况就和头像一样高
    _commenth = (texth < 20) ? 35 : (texth + 20);    
  }
  return _commenth;
}

- (cgfloat)height
{
  if (_height == 0) {
    _height = self.commenth + 20;
    if ([self.isshow isequaltostring:@"1"]) {
      _height += 20;
    }

  }
  return _height;
}

@end

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: