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;

}

相关推荐
凡泰AI1 小时前
如何通过小程序多端框架,让一个小程序同时运行在iOS、安卓、鸿蒙以及PC客户端,实现一次开发多端运行的效果
android·ios·小程序
羽翼安全1 小时前
如何防止电脑显示器被手机拍照泄密?6款防拍屏软件测评
智能手机·计算机外设·电脑
ZacJi13 小时前
当苹果将系统 API 划归 @MainActor:一次跨 SDK 版本的 Swift 并发踩坑与破局实战
ios·swift
mardelan13 小时前
2026年iOS短视频总结工具测评强识别提效率 整理清晰更省心
ios·音视频
ZZH_AI项目交付16 小时前
638 处旧名称残留——Swift/ObjC 混编项目安全重命名完整指南
ios·objective-c·swift
单片机杂货铺16 小时前
基于单片机的智能粮仓控制系统设计与实现
stm32·单片机·嵌入式硬件·物联网·计算机外设·51单片机·课程设计
ZZH_AI项目交付16 小时前
Apple Silicon 模拟器遇到旧版 MLKit:一次完整的依赖排查
ios·app·编译器
kango16 小时前
iOS 项目工程化构成与 Xcode 架构详解
ios·程序员
2501_9159184118 小时前
iOS 怎么抓包?抓包鹰系统级 网卡 应用层三种方式对比,不越狱抓 iPhone 流量
网络协议·计算机网络·网络安全·ios·adb·https·udp
ZZH_AI项目交付20 小时前
一个 33,623 字节的 ViewController——拆开它我用了四步
ios·app·apple