iOS监听键盘事件

本文详细介绍了如何在iOS应用中实现键盘弹出时的视图布局调整,包括获取键盘高度、设置动画平移底部工具栏以保持用户体验的一致性。
#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}#pragma mark - 通知
/**
 *   键盘弹出
 */
- (void)keyboardWillShow:(NSNotification *)note
{
    
    // 1.取出键盘的高度
    CGRect temp  = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat height = temp.size.height;
    // 2.让工具条向上平移
    // 2.1取出键盘弹出的动画时间
    NSTimeInterval timte = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:timte delay:0 options:7 << 16 animations:^{
        self.bottomBar.transform = CGAffineTransformMakeTranslation(0, -height);
    } completion:nil];
    
}
/**
 *  键盘隐藏
 */
- (void)keyboardWillHide:(NSNotification *)note
{
    // 2.1取出键盘弹出的动画时间
    NSTimeInterval timte = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 清空transform
    [UIView animateWithDuration:timte delay:0 options:7 << 16 animations:^{
        
        self.bottomBar.transform = CGAffineTransformIdentity;
    } completion:nil];
    
}

 

转载于:https://www.cnblogs.com/songxing10000/p/4944031.html

### iOS 监听键盘事件iOS 开发中,`NSNotificationCenter` 提供了一种机制来监听软键盘的显示和隐藏通知。通过注册 `UIKeyboardWillShowNotification` 和 `UIKeyboardWillHideNotification` 可以获取到键盘即将显示或隐藏的信息[^1]。 下面是一段 Swift 代码示例,展示了如何设置观察者并处理相应的通知: ```swift import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 添加键盘将要出现的通知监听器 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear), name: UIResponder.keyboardWillShowNotification, object: nil) // 添加键盘将要消失的通知监听器 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillAppear(notification: Notification) { if let userInfo = notification.userInfo, let keyboardFrameValue = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue { let keyboardFrame = keyboardFrameValue.cgRectValue // 获取键盘高度 let keyboardHeight = keyboardFrame.height print("Keyboard will appear with height \(keyboardHeight)") // 这里可以调整界面布局逻辑 } } @objc func keyboardWillDisappear(notification: Notification) { print("Keyboard will disappear") // 处理键盘收起后的界面恢复操作 } deinit { // 移除所有的通知监听器 NotificationCenter.default.removeObserver(self) } } ``` 此代码片段实现了当键盘即将显现时打印其高度,并允许开发者在此基础上进一步修改视图控制器中的 UI 布局;同样,在键盘即将消失的时候也进行了简单的日志记录以便于追踪状态变化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值