keyboard监听、inputView、inputAccessoryView

    (后面有代码)类似于QQ、微信的聊天界面都有一个自定义的toolBar负责输入和各种功能

    类似这样的都是需要自定义一个UIView负责完成各个控件的组合。那么问题来了,当输入时,键盘弹出,自定义view的frame就要发生相应的改变,下面就来聊聊键盘监听。

    对于键盘的监听一般用到的都是NSNotificationCenter(通知中心),以下是注册一个通知中心,对于键盘变化的事件标志有UIKeyboardWillShowNotification、UIKeyboardWillHideNotification、UIKeyboardWillChangeFrameNotification等一些比较常用的,我本人在这个例子中使用的是UIKeyboardWillChangeFrameNotification(第三种),这种方法是监听键盘发生变化时做出反应,相对于前面两种会更通用。

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillChangeWithNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];

    在通知的执行方法里通过通知中心的Info获取frame

- (void)keyBoardWillChangeWithNotification:(NSNotification *)noti

{

    NSDictionary *keyBoardInfo = [noti userInfo];

    //通知中心根据keyboard的变化拿到frame转化成rect

    CGRect keyBoardFrame = [[keyBoardInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    //计算出keyboard弹出时间:0.25

    CGFloat keyBoardAnimation = [[keyBoardInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];

    [UIView animateWithDuration:keyBoardAnimation animations:^{

        if (keyBoardFrame.origin.y > self.view.frame.size.height) {

            //键盘没出来

            self.inputToolBar.y = keyBoardFrame.origin.y - self.inputToolBar.frame.size.height;


        }else{

            //键盘出来

            self.inputToolBar.y = keyBoardFrame.origin.y - self.inputToolBar.frame.size.height;

        }

    }]; 

}

以上是自定义view时对键盘的监听。

下面是在使用UITextView和UITextField的时候,通过inputAccessoryView属性给输入时呼出的键盘加一个附属视图(一般为UIToolbar),inputView给一个输入方式,如果不是UITextView或UITextField,inputAccessoryView和inputView为readonly的。

    /**

     demo 里的这个ViewController主要是为了介绍textViewtextFieldinputViewinputAccessView的自定义样式

     

     inputAccessView继承与UIView 一般我们都给将一个UIToolbar (工具栏)

     inputView则是输入方式,可以是系统给的键盘输入,也可以是自己给定的一种输入方式

     

     当键盘回收时,inputAccessView inputView 都会消失

     */

    // UIToolBar items 放的都是 UIBarButtonItem

    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];

    UIBarButtonItem *cancelBarButton = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarButtonEvents)];

    cancelBarButton.tintColor = [UIColor redColor];

    UIBarButtonItem *spaceBarButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];// 用来布局对齐

    UIBarButtonItem *doBarButton = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(doBarButtonEvents)];

    doBarButton.tintColor = [UIColor orangeColor];

    toolBar.items = @[cancelBarButton,spaceBarButton,doBarButton];

    //在键盘输入位置的View样式

    UIPickerView *pickerView = [[UIPickerView alloc]init];

    pickerView.delegate = self;

    pickerView.dataSource = self;

    //输入方式

    self.textView.inputView = pickerView;

    // 在键盘上的工具条

    self.textView.inputAccessoryView = toolBar;

以上两种方式在开发过程中还是比较常用的,尤其是IM

在后面会附上代码,方便查阅


### 使用Python实现键盘事件监听 对于在Python中实现键盘事件监听,推荐使用`pynput`库[^2]。此库兼容Python 3.x版本,并提供了简单易用的接口用于捕获键盘输入。 #### 安装依赖包 为了开始编写代码,在本地环境中安装必要的软件包是第一步: ```bash pip install pynput ``` #### 键盘监听示例代码 下面是一个简单的例子展示如何设置一个监听器来记录按下的键并打印出来: ```python from pynput.keyboard import Listener, Key def on_press(key): try: print(f'Key {key.char} pressed') except AttributeError: print(f'Special key {key} pressed') with Listener(on_press=on_press) as listener: listener.join() ``` 这段程序创建了一个监听器对象,当检测到按键动作时会触发`on_press()`方法。该方法尝试访问被按下键的具体字符表示;如果是特殊键(比如Ctrl、Shift),则直接返回键名而不抛出异常。 #### 处理特殊情况 有时可能还需要处理其他类型的交互行为,如停止监听或响应特定组合键。可以扩展上述逻辑以满足更复杂的需求: ```python import keyboard # 可选方案之一,提供额外功能支持 def stop_listening(): print("Stopping the listener...") return False # 返回False可终止Listener循环 # 修改后的on_press函数加入退出条件判断 def on_press_with_exit(key): if key == Key.esc: # 当按下ESC键时调用stop_listening()结束监听 return stop_listening() try: print(f'alphanumeric key {key.char} pressed') except AttributeError: print(f'special key {key} pressed') with Listener(on_press=on_press_with_exit) as listener: listener.join() ``` 在这个改进版的例子中引入了新的机制允许用户通过按下Esc键优雅地中止监听过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值