我已实施keyboardWillShow:
和keyboardWillHide:
次通知。我正在注册通知,直接触摸UITextField
上的屏幕后它们工作正常,但是有问题。在我的viewDidLoad
注册通知后,我正在呼叫becomeFirstResponder
。键盘弹出但keyboardWillShow:
没有被调用(如上所述,只是第一次。从您调用函数注册通知及其实际时间开始,似乎存在延迟注册,我不应该延迟执行becomeFirstResponder
)。有什么想法吗?
@objc func keyboardWillShow(_ notification: NSNotification) {
print("Show")
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset: UIEdgeInsets = self.tv_main.contentInset
contentInset.bottom = keyboardSize.height
self.tv_main.contentInset = contentInset
let indexpath = IndexPath(row: 0, section: 0)
self.tv_main.scrollToRow(at: indexpath, at: UITableViewScrollPosition.top, animated: true)
}
}
@objc func keyboardWillHide(_ notification: NSNotification) {
print("Hide")
if let _ = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let contentInset:UIEdgeInsets = UIEdgeInsets.zero
self.tv_main.contentInset = contentInset
}
}
override func viewDidLoad() {
super.viewDidLoad()
tv_main.delegate = self
tv_main.dataSource = self
tf_search.delegate = self
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)
self.tf_search.becomeFirstResponder()
if let placeholder = tf_search.placeholder {
tf_search.attributedPlaceholder = NSAttributedString(string:placeholder, attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
}
}
答案 0 :(得分:5)
您应该在NotificationCompat.Builder
或becomeFirstResponder
或viewWillAppear
中致电viewDidAppear
。