iOS UI基础-10.0 QQ聊天布局之键盘及文本使用

时间:2023-03-08 22:05:09

要实现的效果:

iOS UI基础-10.0 QQ聊天布局之键盘及文本使用  iOS UI基础-10.0 QQ聊天布局之键盘及文本使用

这里只说用到的几个知识点

1.图片包含文字

在设置文字的Frame的时候,使用背景(按钮)的尺寸,文字使用了内边距

背景图片,使用拉伸

/**
* 返回一张可以随意拉伸不变形的图片
*
* @param name 图片名字
*/
+ (UIImage *)resizableImage:(NSString *)name
{
UIImage *normal = [UIImage imageNamed:name];
CGFloat w = normal.size.width * 0.5;
CGFloat h = normal.size.height * 0.5;
return [normal resizableImageWithCapInsets:UIEdgeInsetsMake(h, w, h, w)];
}

使用的时候:

   [self.textView setBackgroundImage:[UIImage resizableImage:@"chat_send_nor"] forState:UIControlStateNormal];

2. 给输入框增加空格符

iOS UI基础-10.0 QQ聊天布局之键盘及文本使用

    //  设置文本框左边显示的view
self.inputView.leftView = [[UIView alloc] initWithFrame:CGRectMake(, , , )];
// 永远显示
self.inputView.leftViewMode = UITextFieldViewModeAlways;

3.给输入框的键盘设置发送按钮

iOS UI基础-10.0 QQ聊天布局之键盘及文本使用

设置为send ,并打上勾,如下图

iOS UI基础-10.0 QQ聊天布局之键盘及文本使用

实现代理UITextFieldDelegate,部分代码

@interface MJViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *inputView;
@end @implementation MJViewController - (void)viewDidLoad
{
[super viewDidLoad]; // 设置文本框代理
self.inputView.delegate = self;
} #pragma mark - 文本框代理
/**
* 点击了return按钮(键盘最右下角的按钮)就会调用
*/
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
// 1.自己发一条消息
[self addMessage:textField.text type:MJMessageTypeMe]; // 2.自动回复一条消息
NSString *reply = [self replayWithText:textField.text];
[self addMessage:reply type:MJMessageTypeOther]; // 3.清空文字
self.inputView.text = nil; // 返回YES即可
return YES;
}

4.键盘显示和关闭

在viewDidLoad中,监听键盘

    // 2.监听键盘的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

keyboardWillChangeFrame方法

/**
* 当键盘改变了frame(位置和尺寸)的时候调用
*/
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
// 设置窗口的颜色
self.view.window.backgroundColor = self.tableView.backgroundColor; // 0.取出键盘动画的时间
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; // 1.取得键盘最后的frame
CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; // 2.计算控制器的view需要平移的距离
CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height; // 3.执行动画
[UIView animateWithDuration:duration animations:^{
self.view.transform = CGAffineTransformMakeTranslation(, transformY);
}];
}

关闭键盘

/**
* 当开始拖拽表格的时候就会调用
*/
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
// 退出键盘
[self.view endEditing:YES];
}