![](/img/trans.png)
[英]How to make a UIScrollView auto scroll when a UITextField becomes a first responder
[英]How to change UIScrollView contentSize after UITextField resigns first responder
我正在寫一個iPhone應用程序,我有一些UITextfields,當鍵盤出現時會被覆蓋; 因此我將UITextField放在UIScrollView
,並將自己設置為委托,以便在鍵盤變為活動狀態時調用此方法:
-(void) textFieldDidBeginEditing:(UITextField *)textField
{
self.myScrollView.contentSize = CGSizeMake(self.myScrollView.contentSize.width, 560);
[self.myScrollView setContentOffset:CGPointMake(0, 200) animated:YES];
}
請注意,我正在使contentSize更高,以便即使文本字段成為焦點,用戶仍然可以滾動。
同樣,當textfield重新響應第一個響應者狀態時,會調用此方法:
-(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動畫沒有時間完成。 相反,動畫看起來非常生澀。 有什么建議么?
使用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];
第2步:在鍵盤顯示時執行某些操作
- (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];
}
}
第3步:鍵盤確實隱藏時做一些事情
// 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,只需調整視圖的位置,通過動畫,它看起來很棒。
那這個呢? 不知道它是否會起作用,但只是從我的頭腦中:
[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];
}];
祝好運
您可以嘗試使用scrollRectToVisible:animated:而不是設置內容偏移量,並將其傳遞給文本字段或CGRectZero
的矩形,具體取決於您要去的方向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.