我有两个UITextViews,一个位于UIView顶部的另一个UIView底部. 我使用此代码,在键盘出现时移动UIView. - (void) viewDidLoad{[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow) na
我使用此代码,在键盘出现时移动UIView.
- (void) viewDidLoad { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil]; } -(void)keyboardWillShow { // Animate the current view out of the way [UIView animateWithDuration:0.3f animations:^ { self.frame = CGRectMake(0, -160, 320, 480); }]; } -(void)keyboardWillHide { // Animate the current view back to its original position [UIView animateWithDuration:0.3f animations:^ { self.frame = CGRectMake(0, 0, 320, 480); }]; }
当我从底部使用UITextView时,它工作得很好.但是我的问题是,当我想使用UIView顶部的UITextView时,键盘出现,UIView向上移动,但我的顶级UITextView也向上移动.请帮助我,如果用户想要从顶部在UITextView上键入文本,我不想移动UIView.
我在项目中使用的一个非常简单的方法是TPKeyboardAvoiding库.https://github.com/michaeltyson/TPKeyboardAvoiding
下载源代码,将4个文件放入项目中.在InterfaceBuilder中,确保TextViews位于UIScrollView或UITableView中,然后将该滚动视图或tableview的类更改为TPAvoiding子类.
如果您不想这样做,您的另一个选择是检查正在使用哪个TextView,并且仅在您想要的键盘是选定的键盘时设置动画,即:
-(void)keyboardWillShow { // Animate the current view out of the way if ([self.textFieldThatNeedsAnimation isFirstResponder]) { [UIView animateWithDuration:0.3f animations:^ { self.frame = CGRectMake(0, -160, 320, 480); }]; self.animated = YES; } } -(void)keyboardWillHide { // Animate the current view back to its original position if (self.animated) { [UIView animateWithDuration:0.3f animations:^ { self.frame = CGRectMake(0, 0, 320, 480); }]; self.animated = NO; } }