iOS 键盘相关

1.键盘出现消失时,参考的view变化的代码:

  • (void)viewDidLoad {

superviewDidLoad;

// Do any additional setup after loading the view.

__weaktypeof(self) weakSelf =self;

_textField= UITextField new;

_textField.backgroundColor = UIColor redColor;

self.view addSubview:_textField;

[_textField mas_makeConstraints:^(MASConstraintMaker *make) {

//left,right,centerx,y不能共存只能有其二

make.left.mas_equalTo(20);

//make.right.mas_equalTo(-60);

make.centerX.equalTo(weakSelf.view);

make.height.mas_equalTo(40);

make.bottom.mas_equalTo(0);

}];

//注册键盘通知

\[NSNotificationCenter defaultCenter addObserver:selfselector:@selector(keyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];

\[NSNotificationCenter defaultCenter addObserver:selfselector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];

}

  • (void)keyboardWillChangeFrameNotification:(NSNotification *)notification {

//获取键盘基本信息(动画时长与键盘高度)

NSDictionary *userInfo = notification userInfo;

CGRect rect = userInfo\[UIKeyboardFrameBeginUserInfoKey CGRectValue];

CGFloat keyboardHeight= CGRectGetHeight(rect);

CGFloat keyboardDuration = userInfo\[UIKeyboardAnimationDurationUserInfoKey doubleValue];

//修改下边距约束

[_textField mas_updateConstraints:^(MASConstraintMaker *make) {

make.bottom.mas_equalTo(-keyboardHeight);

}];

//更新约束

[UIView animateWithDuration:keyboardDuration animations:^{

self.view layoutIfNeeded;

}];

}

  • (void)keyboardWillHideNotification:(NSNotification *)notification {

//获得键盘动画时长

NSDictionary *userInfo= notification userInfo;

CGFloat keyboardDuration = userInfo\[UIKeyboardAnimationDurationUserInfoKey doubleValue];

//修改为以前的约束(距下边距0)

[_textField mas_updateConstraints:^(MASConstraintMaker *make) {

make.bottom.mas_equalTo(0);

}];

//更新约束

[UIView animateWithDuration:keyboardDuration animations:^{

self.view layoutIfNeeded;

}];

}

  • (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

supertouchesBegan:touches withEvent:event;

self.view endEditing:YES;

}

相关推荐
择势11 小时前
基于声网 Agora RTM + RTC SDK 实现 iOS 语音聊天室 —— 常见问题汇总 & 解决方案手册
ios
择势11 小时前
基于声网 Agora RTM + RTC SDK 实现 iOS 语音聊天室(进阶封装)
ios
择势12 小时前
基于声网 Agora RTM + RTC SDK 实现 iOS 语音聊天室——从零到可跑的指南
ios
白玉cfc12 小时前
【iOS】底层原理:类的加载
ios·objective-c·xcode
один but you13 小时前
【无标题】
macos·objective-c·cocoa
科技每日热闻14 小时前
EVNIA弈威天王星舒视蓝4.0系列护眼显示器24M2N2200PK新品——小而强悍,久战不倦!
科技·游戏·计算机外设
光电的一只菜鸡14 小时前
shell脚本开发技巧
开发语言·ios·swift
2501_9160074715 小时前
iOS应用性能优化全面指南:从内存管理到工具使用
android·ios·性能优化·小程序·uni-app·iphone·webview
库奇噜啦呼16 小时前
【iOS】源码学习-类的加载
学习·ios·cocoa
ayqy贾杰16 小时前
我同事,40了,他vibe coding了个App
前端·ios·客户端