我在将 UISearchBar 设置为其自己的输入附件视图时遇到了类似的问题。第一次点击 - 栏会移动,第二次点击 - 键盘显示。关闭键盘完全从屏幕上移除了该栏。我的解决方案是手动响应键盘显示和隐藏通知,并取消输入附件。然后我会相应地为栏设置动画。如果您的搜索栏不像我的那样位于底部,您将不得不根据您的需要定制动画。我希望这是有帮助的!
在 viewDidLoad 中:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
其他方法:
- (NSTimeInterval)keyboardAnimationDurationForNotification:(NSNotification*)notification {
NSDictionary* info = [notification userInfo];
NSValue* value = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval duration = 0;
[value getValue:&duration];
return duration;
}
-(void)keyboardWillShow:(NSNotification*)n {
CGRect frame = CGRectMake(self.mSearchBar.frame.origin.x, self.mSearchBar.frame.origin.y - 216, self.mSearchBar.frame.size.width, self.mSearchBar.frame.size.height);
[UIView animateWithDuration:[self keyboardAnimationDurationForNotification:n] delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
self.mSearchBar.frame = frame;
} completion:nil];
}
-(void)keyboardWillHide:(NSNotification*)n {
CGRect frame = CGRectMake(self.mSearchBar.frame.origin.x, self.mSearchBar.frame.origin.y + 216, self.mSearchBar.frame.size.width, self.mSearchBar.frame.size.height);
[UIView animateWithDuration:[self keyboardAnimationDurationForNotification:n] delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
self.mSearchBar.frame = frame;
} completion:nil];
}
完成后移除观察者是个好主意(可能在 viewDidUnload 中):
[[NSNotificationCenter defaultCenter] removeObserver:self];