当键盘出现时移动UIView

3
我有两个UITextView,一个位于UIView的顶部,另一个位于UIView的底部。
我使用以下代码在键盘出现时移动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也向上移动了。请帮助我,我不想在用户想从顶部输入文本时移动UIView。

1个回答

7

在我的项目中,我使用的一种非常简单的方法是TPKeyboardAvoiding库。

https://github.com/michaeltyson/TPKeyboardAvoiding

下载源代码,将4个文件放入您的项目中。在InterfaceBuilder中,确保您的TextViews位于UIScrollView或UITableView中,然后更改该滚动视图或表视图的类为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;
    }
}

1
非常好的答案。非常感谢。如此简单,如此快速。我喜欢它。 - iDev_91
1
这很好用,除非你试图减少应用程序的内存占用。请注意,向UIScrollView添加子视图是昂贵的,并且可能会大幅增加内存使用量。 - Sam Spencer
好的,如果您不想要那些额外开销,可以像我在答案中提到的那样手动动画处理您的视图(但是如果您使用自动布局,代码将会有所不同)。 - powerj1984

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接