我有六个UITextFields在我的视图中,我想决定是否移动视图。在移动视图之前,如何检查哪个TextField被选中?
这是我的代码来显示键盘并移动视图:
这是我的代码来显示键盘并移动视图:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.view.frame.origin.y -= keyboardSize.height - 85
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.view.frame.origin.y += keyboardSize.height - 85
}
}
override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillShow(notification: NSNotification) { if let userInfo = notification.userInfo, let keyboardSize = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) scrollView.contentInset = contentInsets scrollView.scrollIndicatorInsets = contentInsets var frame = view.frame frame.size.height -= keyboardSize.height if let activeField = activeField, !frame.contains(activeField.frame.origin) { let scrollPoint = CGPoint(x: 0, y: activeField.frame.origin.y - keyboardSize.height) scrollView.setContentOffset(scrollPoint, animated: true) } } } @objc func keyboardWillHide(notification: NSNotification) { let contentInsets = UIEdgeInsets.zero scrollView.contentInset = contentInsets scrollView.scrollIndicatorInsets = contentInsets } func textFieldDidBeginEditing(_ textField: UITextField) { activeField = textField } func textFieldDidEndEditing(_ textField: UITextField) { activeField = nil }
- Akash