【问题标题】:I want to change my view's frame when the keyboard shows我想在键盘显示时更改视图的框架
【发布时间】:2018-09-17 13:02:53
【问题描述】:

这是我添加观察者的函数

func subscribeToKeyboardNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
}

但是.UIKeyboardWillShow 给了我一个错误

'UIKeyboardWillShow' 已重命名为 'UIResponder.keyboardWillShowNotification'

将“UIKeyboardWillShow”替换为 'UIResponder.keyboardWillShowNotification'

但是当我替换它时

func subscribeToKeyboardNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIResponder.keyboardWillShowNotification, object: nil)
}

我收到这个错误

没有更多上下文的表达类型是模棱两可的

【问题讨论】:

标签: ios swift swift4.2


【解决方案1】:

没有点

NotificationCenter.default.addObserver(self, 
selector: #selector(keyboardWillShow), 
name: UIResponder.keyboardWillShowNotification, object: nil)

【讨论】:

  • 我猜第二个解决方案行不通 (Type 'NSNotification.Name?' has no member 'keyboardWillShowNotification')。
  • @AndréSlotta 实际上没有尝试过,但 op 会提供反馈
  • 它可以工作,但 or 部分并不太感谢
【解决方案2】:
let notificationCenter = NotificationCenter.default

notificationCenter.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { (notification) in
                self.keyboardWillShow(notification: notification)
            }
notificationCenter.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil) { (notification) in
                self.keyboardWillHide(notification: notification)
            }

【讨论】:

    【解决方案3】:

    只需导入模块UIKit,因为UIResponderUIKit 的一部分,而不是Foundation 模块

    SWIFT 5 代码

    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            addObservers()
        }
    
        public func addObservers() {
            NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        }
    
        @objc func handleKeyboardWillShow(_: Notification) {
            // Here handle keyboard
        }
    }
    

    【讨论】:

      【解决方案4】:

      我用过这个,效果很好

      NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowOrHide(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
      

      【讨论】:

      • Swift 4.2 中没有
      猜你喜欢
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 2014-02-14
      • 2016-01-08
      • 2015-04-01
      相关资源
      最近更新 更多