-(void) textFieldDidBeginEditing:(UITextField *)textField
{
self.myScrollView.contentSize = CGSizeMake(self.myScrollView.contentSize.width, 560);
[self.myScrollView setContentOffset:CGPointMake(0, 200) animated:YES];
}请注意,我将contentSize设置得更高,这样即使文本字段成为焦点,用户仍然可以滚动。
类似地,当文本字段放弃first responder状态时,将调用此方法:
-(void) textFieldDidEndEditing:(UITextField *)textField
{
[self.myScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
self.myScrollView.contentSize = CGSizeMake(self.myScrollView.contentSize.width,self.myScrollView.frame.size.height);
}请注意,一旦放下键盘,所有内容都是可见的,因此不需要启用滚动(contentSize = frame.size)。
但是,我的问题是因为我是在设置contentOffset之后设置contentSize的,所以setContentOffset动画没有时间完成。取而代之的是,动画看起来非常颠簸。有什么建议吗?
发布于 2013-02-20 11:45:19
使用UIKeyboardDidShowNotification和UIKeyboardWillHideNotification是一个好主意:
第1步:收听两个通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];第二步:在键盘显示的时候做点什么
- (void)keyboardDidShow:(NSNotification*)notification
{
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
BOOL Need_Resize; // judge by yourself
if (Need_Resize) {
double offset; // judge by yourself
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.5];
[UIView setAnimationBeginsFromCurrentState:YES];
[self.view setCenter:CGPointMake(self.view.center.x, self.view.center.y - offset];
[UIView commitAnimations];
}
}第三步:在键盘隐藏的时候做点什么
// in animation code, set the view back to the original place
[self.view setCenter:CGPointMake(self.view.center.x, self.view.frame.size.height/2)];这个解决方案不需要UIScrollView,只需要调整视图的位置,加上动画,看起来就足够棒了。
发布于 2013-02-20 11:44:31
那这个呢?不知道它是否有效,但从我的头顶上看:
[UIView animateWithDuration:0.5
animations:^{
self.myScrollView.contentSize = CGSizeMake(self.myScrollView.contentSize.width, 560);
} completion:^(BOOL finished) {
[self.myScrollView setContentOffset:CGPointMake(0, 200) animated:YES];
}];祝好运
发布于 2013-02-20 11:52:23
您可以不设置内容偏移量,而是尝试使用scrollRectToVisible:animated:并将文本字段或CGRectZero的rect传递给它,这取决于您要使用的方向。
https://stackoverflow.com/questions/14971576
复制相似问题