我當前使用此方法在屏幕上有多個文本字段並且不希望鍵盤隱藏文本字段時向上和向下滾動視圖。我在網上發現了這個代碼,大部分工作情況非常好。xCode TextField在編輯時按下主屏幕按鈕時出現的鍵盤視圖滾動問題
在實施
static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;
然後我用這些方法來使視圖上下滾動點擊文本字段時,接口文件
@interface ViewController : UIViewController<UITextFieldDelegate>
{
IBOutlet UITextField *textField1;
IBOutlet UITextField *textField2;
IBOutlet UITextField *textField3;
//Float
CGFloat animatedDistance;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
CGFloat heightFraction = numerator/denominator;
if (heightFraction < 0.0)
{
heightFraction = 0.0;
}
else if (heightFraction > 1.0)
{
heightFraction = 1.0;
}
UIInterfaceOrientation orientation =
[[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait ||
orientation == UIInterfaceOrientationPortraitUpsideDown)
{
animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
}
else
{
animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
}
CGRect viewFrame = self.view.frame;
viewFrame.origin.y -= animatedDistance;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
[self.view setFrame:viewFrame];
[UIView commitAnimations];
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
CGRect viewFrame = self.view.frame;
viewFrame.origin.y += animatedDistance;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
[self.view setFrame:viewFrame];
[UIView commitAnimations];
}
在這個例子中,我有3個文本字段,位於屏幕頂部,屏幕中間和底部的屏幕。我還將這個工具欄添加到每個文本字段中,並在其中包含前一個和完成的按鈕。我相信你可以猜到他們做了什麼。
此代碼適用於除一個問題外。如果我正在編輯文本字段,並且單擊屏幕中間的文本字段,則視圖向上滾動以便文本字段不隱藏,這很好。但是,如果我在編輯過程中單擊主頁按鈕,然後再次訪問應用程序,當再次打開視圖時,滾動將重置爲通常的方式,但文本字段仍在編輯中,所以當我做點擊完成按鈕,視圖的行爲是如果它仍然向上滾動,所以它再次向下滾動,這導致視圖滾動屏幕底部
我也嘗試使用鍵盤上的通知被顯示或隱藏以滾動視圖,但同樣的問題發生。
有沒有人有過這個問題?如果是這樣,他們是如何解決它的。
在此先感謝
稍後回覆,已關閉工作5天,並且無法訪問mac,因此無法測試。非常感謝,您的解決方案完美無缺! – AdamM