Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何检测键盘何时显示和隐藏_Ios_Iphone_Iphone Sdk 3.0 - Fatal编程技术网

Ios 如何检测键盘何时显示和隐藏

Ios 如何检测键盘何时显示和隐藏,ios,iphone,iphone-sdk-3.0,Ios,Iphone,Iphone Sdk 3.0,如何检测键盘在我的应用程序中何时显示和隐藏?查看“文本、Web和编辑编程指南”部分,了解有关跟踪显示或隐藏的键盘以及如何手动显示/取消键盘的信息。您需要注册两个键盘通知: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name: UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter

如何检测键盘在我的应用程序中何时显示和隐藏?

查看“文本、Web和编辑编程指南”部分,了解有关跟踪显示或隐藏的键盘以及如何手动显示/取消键盘的信息。

您需要注册两个键盘通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name: UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidHide:) name: UIKeyboardDidHideNotification object:nil];

关于如何将文本字段调整到键盘的精彩文章-

在类的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];
然后,在您指定的方法中(在本例中为
keyboardidshow
keyboardidhide
),您可以对此采取一些措施:

- (void)keyboardDidShow: (NSNotification *) notif{
    // Do something here
}

- (void)keyboardDidHide: (NSNotification *) notif{
    // Do something here
}

你们可以使用图书馆。它包含一些示例并提供简单的界面。

您可能只需要在
viewDidLoad
中添加观察者。但是在
视图中使用
addObserver
将出现
,在
视图中使用
removeObserver
将消失
可以防止在更改视图时发生罕见的崩溃

Swift 4.2 Swift 3和4 老斯威夫特 Swift 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
}

如果您有多个
UITextField
s,并且需要在键盘出现或消失时(或之前)执行某些操作,则可以实现此方法

UITextFieldDelegate
添加到类中。分配整数计数器,例如:

NSInteger editCounter; 
viewDidLoad
中的某个位置将此计数器设置为零。 然后,实现
textfieldshouldinediting
textfieldshouldenediting
委托方法

在第一个示例中,向editCounter添加1。如果editCounter的值变为1-这意味着将显示键盘(如果您返回YES)。如果editCounter>1-这意味着键盘已可见,另一个UITextField保持焦点

textfield中,应取消编辑
从编辑计数器中减去1。如果您得到零-键盘将被取消,否则它将保留在屏幕上。

Swift 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)
}

Swift 4-
2017年10月20日

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)
}
Swift-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) {

}

在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.
    }
}

这里有一个CocoaPods,便于观察
NSNotificationCentr
键盘的可见性:

pod'Keyhi'

Swift 5 上面的答案是正确的。尽管我更愿意创建一个助手来包装
通知的观察者

好处:
  • 您不必每次处理键盘行为时都重复
  • 您可以通过实现其他枚举值来扩展其他通知
  • 当您必须在多个控制器中处理键盘时,它非常有用
  • 示例代码: 如何使用:
    }所以啊,这才是真正的答案

    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() },
            ]
        }
    }
    
    导入联合收割机
    类MrEnvironmentObject{
    ///绑定到您的SwiftUI视图中
    @发布的公共变量iskeyboard显示:Bool=false
    ///不要让他们放弃
    var订户:[anycancelable]?=nil
    ///添加某些联合收割机订阅服务器,这些订阅服务器将处理更新
    ///`isKeyboardShowing`属性
    ///
    ///-参数主机:视图的UIHostingController。
    功能设置订阅者(
    主机:inout UIHostingController
    ) {
    订户=[
    通知中心
    违约
    .publisher(用于:UIResponder.keyboardWillShowNotification)
    .sink{[弱自我]uu
    self?.isKeyboardShowing=真
    },
    通知中心
    违约
    .publisher(用于:UIResponder.keyboardWillHideNotification)
    .sink{[弱自我,弱主机]\uin
    self?.isKeyboardShowing=false
    //隐藏的宝石,问我怎么知道:
    UIP.post(
    通知:。布局已更改,
    参数:主机
    )
    },
    // ...
    利润
    .sink{[弱自我]利润中的利润(),
    ]
    }
    }
    
    如果通过字段进行制表,则不起作用。想知道解决这个问题的方法是什么,你甚至可以在一台真正的iPad上进行tab-thru吗?@学徒你的意思是键盘不会显示你是否进行了tab?如果在有焦点的区域下方仍有键盘覆盖的区域,视图将保持在选项卡上,因为只有在键盘滑动时才发送通知up@apprentice您必须手动管理,根据每个文本字段变为活动状态来滑动滚动视图,这与知道键盘何时出现不同。将视图控制器设为
    UITextFieldDelegat
    e,然后实现
    textFieldShouldReturn:
    方法。您将获得刚刚作为参数输入的
    文本字段
    ,您可以将其与自己的文本字段进行比较,并滚动
    滚动视图
    ,以便显示相应的文本字段。如果在视图中删除观察者,则该文本字段将消失。。。您应该将其添加到ViewWillDisplay而不是viewDidLoad中。这是事实,请随意编辑答案。我会接受的it@FouZ像这样从
    deinit
    删除观察者是否更好:
    deinit{NSNotificationCenter.defaultCenter().removeObserver(self,name:UIKeyboardWillShowNotification,object:nil)NSNotificationCenter.defaultCenter().removeObserver(self,name:UIKeyboardWillHideNotification,object:nil)}
    在Swift 3中,上述Denit代码块类似于:
    Denit{NotificationCenter.default.removeObserver(self,名称:NSNotification.name.UIKeyboardWillShow,对象:nil)NotificationCenter.default.removeObserver(self,名称:NSNotification.name.UIKeyboardWillHide,对象:nil)}
    @Crashalot在您关闭v之前,Denit不会运行
    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) {
    
    }
    
    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.
        }
    }
    
    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")
            }
        }
    
    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() },
            ]
        }
    }