我已实施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])
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
399 次 |
| 最近记录: |