iOS Swift检测键盘事件 [英] iOS Swift detect keyboard events

查看:229
本文介绍了iOS Swift检测键盘事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以以某种方式检测到iOS键盘上的事件吗?

Can I somehow detect events from iOS keyboard?

我想在没有UITextField或任何这类对象的UIViewController上检测此类事件.

I would like to detect this kind of events on the UIViewController which does not have UITextField or any sort of this kind of objects.

我只有四个圆圈,它们是UIView,我想在按下键盘上的按钮时用不同的颜色绘制它们.

All I have are four circles that are UIView and I would like to paint them in different colour when the button on the keyboard is pressed.

推荐答案

您没有任何对象可以接收来自键盘的输入.要使键盘出现,视图中必须具有UITextField或UITextView对象.

You are not having any object to take the input from the keyboard. To make the keyboard appear, you must have either UITextField or UITextView object in your view.

但这是在视图控制器中检测键盘事件的过程.您可以在视图控制器上设置观察者以获取键盘通知.

But here is the process to detect the keyboard events in your view controller. You can set observers on view controller for keyboard notifications.

要在swift 3中注册键盘通知,请在视图控制器的viewDidLoad()或viewWillAppear()方法中编写这些行

To register for keyboard notification in swift 3, use write these lines in viewDidLoad() or viewWillAppear() method of your view controller

    NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)

然后在视图控制器中实现两个方法keyBoardWillHide(:)和keyBoardWillShow(:)方法

And then implement two methods keyBoardWillHide(:) and keyBoardWillShow(:) method in your view controller

    func keyBoardWillShow(notification: NSNotification) {
            //handle appearing of keyboard here
    }


    func keyBoardWillHide(notification: NSNotification) {
              //handle dismiss of keyboard here
     }

这篇关于iOS Swift检测键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆