Answers:
在类的ViewDidLoad方法中,设置为侦听有关键盘的消息:
// Listen for keyboard appearances and disappearances
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
然后,在您指定的方法(在本例中为keyboardDidShow
和keyboardDidHide
)中,您可以对此做一些事情:
- (void)keyboardDidShow: (NSNotification *) notif{
// Do something here
}
- (void)keyboardDidHide: (NSNotification *) notif{
// Do something here
}
UITextFieldDelegat
e,然后实现该textFieldShouldReturn:
方法。您将获得textField
刚刚输入的参数,您可以将其与自己的textFields进行比较并滚动,scrollView
以便显示适当的textField。
您可能只需要addObserver
输入viewDidLoad
。但是,“ addObserver
进入” viewWillAppear
和“ removeObserver
进入” viewWillDisappear
可以防止在更改视图时发生罕见的崩溃。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear), name: UIResponder.keyboardWillShowNotification, object: nil)
}
@objc func keyboardWillAppear() {
//Do something here
}
@objc func keyboardWillDisappear() {
//Do something here
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear), name: Notification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear), name: Notification.Name.UIKeyboardWillShow, object: nil)
}
@objc func keyboardWillAppear() {
//Do something here
}
@objc func keyboardWillDisappear() {
//Do something here
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillAppear:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillDisappear:", name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillAppear(notification: NSNotification){
// Do something here
}
func keyboardWillDisappear(notification: NSNotification){
// Do something here
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
deinit
:deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) }
deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) }
斯威夫特3:
NotificationCenter.default.addObserver(self, selector: #selector(viewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(viewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
func keyboardWillShow(_ notification: NSNotification){
// Do something here
}
func keyboardWillHide(_ notification: NSNotification){
// Do something here
}
斯威夫特4:
NotificationCenter.default.addObserver( self, selector: #selector(ControllerClassName.keyboardWillShow(_:)),
name: Notification.Name.UIKeyboardWillShow,
object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ControllerClassName.keyboardWillHide(_:)),
name: Notification.Name.UIKeyboardWillHide,
object: nil)
接下来,添加方法以在对象的寿命结束时停止侦听通知:-
Then add the promised methods from above to the view controller:
deinit {
NotificationCenter.default.removeObserver(self)
}
func adjustKeyboardShow(_ open: Bool, notification: Notification) {
let userInfo = notification.userInfo ?? [:]
let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let height = (keyboardFrame.height + 20) * (open ? 1 : -1)
scrollView.contentInset.bottom += height
scrollView.scrollIndicatorInsets.bottom += height
}
@objc func keyboardWillShow(_ notification: Notification) {
adjustKeyboardShow(true, notification: notification)
}
@objc func keyboardWillHide(_ notification: Notification) {
adjustKeyboardShow(false, notification: notification)
}
+=
出现使插图越来越大。
UIResponder.keyboardWillShowNotification
和UIResponder.keyboardWillHideNotification
,键盘信息键为UIResponder.keyboardFrameBeginUserInfoKey
。
斯威夫特-4
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addKeyBoardListener()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self) //remove observer
}
func addKeyBoardListener() {
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil);
}
@objc func keyboardWillShow(_ notification: Notification) {
}
@objc func keyboardWillHide(_ notification: Notification) {
}
请查看“文本,Web和编辑编程指南”的“ 管理键盘”部分,以获取有关跟踪显示或隐藏的键盘以及如何手动显示/关闭键盘的信息。
您将需要注册2个键盘通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name: UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidHide:) name: UIKeyboardDidHideNotification object:nil];
关于如何将TextField调整为键盘的好文章-http: //iosdevelopertips.com/user-interface/adjust-textfield-hidden-by-keyboard.html
在Swift 4.2中,通知名称已移至其他名称空间。所以现在
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addKeyboardListeners()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
func addKeyboardListeners() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
}
@objc private extension WhateverTheClassNameIs {
func keyboardWillShow(_ notification: Notification) {
// Do something here.
}
func keyboardWillHide(_ notification: Notification) {
// Do something here.
}
}
上面的答案是正确的。尽管我更愿意创建一个帮助程序来包装notification's observers
。
extension KeyboardHelper {
enum Animation {
case keyboardWillShow
case keyboardWillHide
}
typealias HandleBlock = (_ animation: Animation, _ keyboardFrame: CGRect, _ duration: TimeInterval) -> Void
}
final class KeyboardHelper {
private let handleBlock: HandleBlock
init(handleBlock: @escaping HandleBlock) {
self.handleBlock = handleBlock
setupNotification()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func setupNotification() {
_ = NotificationCenter.default
.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { [weak self] notification in
self?.handle(animation: .keyboardWillShow, notification: notification)
}
_ = NotificationCenter.default
.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { [weak self] notification in
self?.handle(animation: .keyboardWillHide, notification: notification)
}
}
private func handle(animation: Animation, notification: Notification) {
guard let userInfo = notification.userInfo,
let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
else { return }
handleBlock(animation, keyboardFrame, duration)
}
}
private var keyboardHelper: KeyboardHelper?
...
override func viewDidLoad() {
...
keyboardHelper = KeyboardHelper { [unowned self] animation, keyboardFrame, duration in
switch animation {
case .keyboardWillShow:
print("keyboard will show")
case .keyboardWillHide:
print("keyboard will hide")
}
}
}
斯威夫特4 -dd 20 october 2017
override func viewDidLoad() {
[..]
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
}
@objc func keyboardWillAppear(_ notification: NSNotification) {
if let userInfo = notification.userInfo,
let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue).cgRectValue {
let inset = keyboardFrame.height // if scrollView is not aligned to bottom of screen, subtract offset
scrollView.contentInset.bottom = inset
scrollView.scrollIndicatorInsets.bottom = inset
}
}
@objc func keyboardWillDisappear(_ notification: NSNotification) {
scrollView.contentInset.bottom = 0
scrollView.scrollIndicatorInsets.bottom = 0
}
deinit {
NotificationCenter.default.removeObserver(self)
}
如果您的UITextField
键盘数大于1,并且需要在键盘出现或消失时(或之前)执行某些操作,则可以实施此方法。
添加UITextFieldDelegate
到您的课程。分配整数计数器,假设:
NSInteger editCounter;
将此计数器设置为零viewDidLoad
。然后,实现textFieldShouldBeginEditing
并textFieldShouldEndEditing
委托方法。
在第一个中,将1添加到editCounter。如果editCounter的值变为1-这表示将出现键盘(如果返回YES)。如果editCounter> 1-这意味着键盘已经可见,并且另一个UITextField保持焦点。
在textFieldShouldEndEditing
从editCounter减去1。如果您得到零-键盘将被关闭,否则它将保留在屏幕上。
您可以使用KBKeyboardObserver库。它包含一些示例,并提供了简单的界面。
这里有一个CocoaPods可以方便观察NSNotificationCentr
键盘的可见性:https : //github.com/levantAJ/Keyhi
pod 'Keyhi'
所以啊,这才是真正的答案。
import Combine
class MrEnvironmentObject {
/// Bind into yr SwiftUI views
@Published public var isKeyboardShowing: Bool = false
/// Keep 'em from deallocatin'
var subscribers: [AnyCancellable]? = nil
/// Adds certain Combine subscribers that will handle updating the
/// `isKeyboardShowing` property
///
/// - Parameter host: the UIHostingController of your views.
func setupSubscribers<V: View>(
host: inout UIHostingController<V>
) {
subscribers = [
NotificationCenter
.default
.publisher(for: UIResponder.keyboardWillShowNotification)
.sink { [weak self] _ in
self?.isKeyboardShowing = true
},
NotificationCenter
.default
.publisher(for: UIResponder.keyboardWillHideNotification)
.sink { [weak self, weak host] _ in
self?.isKeyboardShowing = false
// Hidden gem, ask me how I know:
UIAccessibility.post(
notification: .layoutChanged,
argument: host
)
},
// ...
Profit
.sink { [weak self] profit in profit() },
]
}
}