我正在使用NSNotificationCenter
在显示键盘时向上移动主视图框。
但是,我只想在选择一个UITextField
时才能使用它。
这是我到目前为止所做的:
func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.CGRectValue().height
}
func keyboardWillShow(notification: NSNotification) {
self.view.frame.origin.y -= getKeyboardHeight(notification)
}
func keyboardWillHide(notification: NSNotification) {
self.view.frame.origin.y += getKeyboardHeight(notification)
}
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
}
func unsubscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
}
func subscribeToKeyboardHide() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
func unsubscribeToKeyboardHide() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
在ViewWillAppear()
中
self.subscribeToKeyboardNotifications()
self.subscribeToKeyboardHide()
在ViewWillDisappear()
中
self.unsubscribeToKeyboardNotifications()
self.unsubscribeToKeyboardHide()
当我只选择一个特定的UITextField
时,如何使视图向上移动?
答案 0 :(得分:5)
试试这个
if yourTextfield.isEditing{}
或者这个
if yourTextfield.isFirstResponder{}
要检查这是你的文本域
答案 1 :(得分:1)
您可以创建以下扩展程序
extension UIView {
/**
Finds the first responder
:returns: the first responder, or nil if nothing found.
*/
private func findFirstResponder() -> UIView? {
if isFirstResponder() { return self }
else {
for view in subviews as! [UIView] {
if let responder = view.findFirstResponder() {
return responder
}
}
return nil
}
}
}
然后在keyboardWillShow
let textField = UIApplication.sharedApplication().keyWindow?.findFirstResponder() as? UITextField
您现在可以使用当前活动的textField。