標籤:
QQ聊天的簡單的介面的搭建:
1.設定聊天介面的tableView
#pragma mark 設定tableview
- (void)settingTableView {
self.tableView.backgroundColor = [UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1];
self.tableView.dataSource = self;
self.tableView.delegate = self;
// 取消分割線
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
// 取消選中
self.tableView.allowsSelection = NO;
}
2.監聽鍵盤的彈出(通知機制)
// 監聽鍵盤彈出
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KeyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
#pragma mark 彈出或隱藏鍵盤調用的方法
- (void)KeyboardWillChangeFrameNotification:(NSNotification *)noti {
// 擷取鍵盤資訊
NSDictionary *dict = noti.userInfo;
// 擷取當前鍵盤的frame
CGRect keyBoardFrame = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 計算鍵盤移動的距離
CGFloat moveY = keyBoardFrame.origin.y - self.view.bounds.size.height;
// 移動transform
self.view.transform = CGAffineTransformMakeTranslation(0, moveY);
// 滾動到最後一行
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.frameArr.count - 1 inSection:0];
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
3.點擊發送按鈕的事件
#pragma mark 點擊發送事件的通知
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
// 添加cell
[self addMessageWithText:textField.text andMessageType:WDJMessagesTypeMe];
[self addMessageWithText:@"洗洗睡吧" andMessageType:WDJMessagesTypeOther];
// 清空textField內容
textField.text = nil;
return YES;
}
3.1 封裝點擊發送按鈕後的tableView展示介面中添加cell的方法
// 封裝添加cell的方法
- (void)addMessageWithText:(NSString *)text andMessageType:(WDJMessagesType)type {
// 設定模型
WDJMessages *message = [[WDJMessages alloc] init];
// 設定屬性
NSDate *date = [NSDate date];
// 時間格式
NSDateFormatter *gs = [[NSDateFormatter alloc] init];
gs.dateFormat = @"yyyy-MM-dd HH-mm";
NSString *dateName = [gs stringFromDate:date];
message.time = dateName;
message.text = text;
message.type = type;
// 取出上一個模型
WDJMessageFrame *lastFrame = [self.frameArr lastObject];
message.hide = [lastFrame.message.time isEqualToString:message.time];
// 設定frame模型
WDJMessageFrame *frame = [[WDJMessageFrame alloc] init];
frame.message = message;
// 添加到數組模型中
[self.frameArr addObject:frame];
// 重新整理資料
[self.tableView reloadData];
// 添加到最後一行
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.frameArr.count -1 inSection:0];
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
4.設定文本輸入框
#pragma mark 文本輸入框
- (void)settingTextField {
// 設定佔位
UIView *view = [[UIView alloc] init];
view.frame = CGRectMake(0, 0, 8, 0);
self.textField.leftView = view;
// 設定左佔位的顯示模式
self.textField.leftViewMode = UITextFieldViewModeAlways;
// 設定代理
self.textField.delegate = self;
}
QQ的聊天介面搭建