如何使NSNotificationCenter仅在选择某个UITextField时运行

Hor*_*tio 1 iphone cocoa nsnotificationcenter ios swift

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)
}
Run Code Online (Sandbox Code Playgroud)

在ViewWillAppear()中

self.subscribeToKeyboardNotifications()
self.subscribeToKeyboardHide()
Run Code Online (Sandbox Code Playgroud)

在ViewWillDisappear()中

self.unsubscribeToKeyboardNotifications()
self.unsubscribeToKeyboardHide()
Run Code Online (Sandbox Code Playgroud)

当我只选择一个特定的时候,如何使视图向上移动UITextField

Leo*_*Leo 5

试试这个

if yourTextfield.isEditing{}
Run Code Online (Sandbox Code Playgroud)

或这个

if yourTextfield.isFirstResponder{}
Run Code Online (Sandbox Code Playgroud)

要检查这是你的文本字段