当键盘打开时,为什么我的视图会重置其位置?

时间:2015-09-25 12:10:50

标签: ios swift cocoa-touch

我的任务是将文本字段附加到键盘的顶部。当键盘向上移动时,文本字段应随之向上移动。但这不起作用..

//编辑:如果我关闭键盘(使用返回键),文本字段会立即定位在键盘顶部并完全向下移动。

这是我的代码:

    func keyboardWillAppear(notification: NSNotification){
         let userInfo:NSDictionary = notification.userInfo!
         let keyboardSize:CGSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue.size

         var messageFrame:CGRect = self.textField.frame
         messageFrame.origin.y -= keyboardSize.height
         UIView.animateWithDuration(0.25, animations: {self.textField.frame = messageFrame})

}

func keyboardWillDisappear(notification: NSNotification){
         let userInfo:NSDictionary = notification.userInfo!
         let keyboardSize:CGSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue.size

         var messageFrame:CGRect = self.textField.frame
         messageFrame.origin.y += keyboardSize.height
         UIView.animateWithDuration(0.25, animations: {self.textField.frame = messageFrame})

}

2 个答案:

答案 0 :(得分:0)

使用标准代码:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
   textField.inputAccessoryView = CustomView;
   return YES;
}

CustomView - 是UITextField

答案 1 :(得分:0)

我在您的代码中进行了一些更改

func keyboardWillAppear(notification: NSNotification){
         let userInfo:NSDictionary = notification.userInfo!
         let keyboardSize:CGSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue.size

         CGFloat newY = self.textField.frame.origin.y - keyboardSize.height;
         UIView.animateWithDuration(0.25, animations: {
             self.textField.frame = CGRectMake(self.textField.frame.origin.x, newY , self.textField.frame.size.width, self.textField.frame.size.height);
})

}