2012-06-13 3 views
0

У меня есть форма на ipad, которая имеет много текстовых полей и кнопку в конце. Есть некоторые поля, которые попадают под клавиатуру, когда она активна. Чтобы вывести скрытое текстовое поле за клавиатурой, чтобы быть видимым, я использую следующий код.uikeyboard оставляет черную часть сверху навигация

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
[self animateTextField:textField up:YES]; 
} 

- (void)textFieldDidEndEditing:(UITextField *)textField 
{ 
_scrollView.frame=CGRectMake(0, 0, 1024, 655); 
[self animateTextField:textField up:NO]; 
} 

- (void) animateTextField: (UITextField*) textField up: (BOOL) up 
{ 
CGPoint temp = [textField.superview convertPoint:textField.frame.origin toView:nil]; 
UIInterfaceOrientation orientation = 
[[UIApplication sharedApplication] statusBarOrientation]; 
if (orientation == UIInterfaceOrientationPortrait) 
{ 
    // NSLog(@"portrait"); 
    if(up) 
    { 
     int moveUpValue = temp.y+textField.frame.size.height; 
     animatedDis = 264-(1024-moveUpValue-5); 
    } 
} 
else if(orientation == UIInterfaceOrientationPortraitUpsideDown) 
{ 
    if(up) 
    { 
     int moveUpValue = 1004-temp.y+textField.frame.size.height; 
     animatedDis = 264-(1004-moveUpValue-5); 
    } 
} 
else if(orientation == UIInterfaceOrientationLandscapeLeft) 
{ 
    if(up) 
    { 
     int moveUpValue = temp.x+textField.frame.size.height; 
     animatedDis = 352-(768-moveUpValue-5); 
    } 
} 
else 
{ 
    if(up) 
    { 
     int moveUpValue = 768-temp.x+textField.frame.size.height; 
     animatedDis = 352-(768-moveUpValue-5); 
     _scrollView.frame = CGRectMake(0, 0, 1024, 655-240); 
    } 

} 
if(animatedDis>0) 
{ 
    const int movementDistance = animatedDis; 
    const float movementDuration = 0.3f; 
    int movement = (up ? -movementDistance : movementDistance); 
    [UIView beginAnimations: nil context: nil]; 
    [UIView setAnimationBeginsFromCurrentState: YES]; 
    [UIView setAnimationDuration: movementDuration]; 
    if (orientation == UIInterfaceOrientationPortrait) 
    { 
     self.view.frame = CGRectOffset(self.view.frame, 0, movement); 
    } 
    else if(orientation == UIInterfaceOrientationPortraitUpsideDown) 
    { 
     self.view.frame = CGRectOffset(self.view.frame, 0, movement); 
    } 
    else if(orientation == UIInterfaceOrientationLandscapeLeft) 
    { 
     self.view.frame = CGRectOffset(self.view.frame, 0, movement); 
    } 
    else 
    { 
     self.view.frame = CGRectOffset(self.view.frame, 0, movement); 
    } 
    [UIView commitAnimations]; 
} 
} 

Я также пользуюсь прокруткой. Моя проблема в том, что когда клавиатура активна, и я нажимаю свою кнопку, она выводит меня на следующий экран. Теперь, если я вернусь назад, клавиатура будет активна и будут установлены предыдущие анимации. Теперь, если я скрываю клавиатуру, весь вид прокручивается вниз, оставляя черную часть сверху. Как справиться с этой ситуацией?

ответ

0

Хорошо. После долгих исследований я нашел простой метод. Это использование уведомлений. В моем представленииDidLoad я добавил эти две уведомления клавиатуры.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name: UIKeyboardDidShowNotification object:nil]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil]; 

Эти методы 2: селектор

-(void)keyboardWasShown:(NSNotification *)aNotification 
{ 

if (displayKeyboard==YES) { 
    return; 
} 
NSDictionary* info = [aNotification userInfo]; 
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey]; 
//NSValue* aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey]; 
CGSize keyboardSize = [aValue CGRectValue].size; 

NSLog(@"kbw====%fkbh====%f",keyboardSize.width,keyboardSize.height); 

offset = _scrollView.contentOffset; 

CGRect viewFrame = _scrollView.frame; 

NSLog(@"svw====%fsvh===%f",viewFrame.size.width,viewFrame.size.height); 
viewFrame.size.height -= keyboardSize.height-49; 
NSLog(@"new view hgt =====%f",viewFrame.size.height); 
_scrollView.frame = viewFrame; 

CGRect textFieldRect = [activeField frame]; 
textFieldRect.origin.y += 10; 
[_scrollView scrollRectToVisible: textFieldRect animated:YES]; 
displayKeyboard = YES; 
} 
-(void)keyboardWillBeHidden:(NSNotification *)aNotification 
{ 

if (!displayKeyboard) { 
    return; 
} 

_scrollView.frame = CGRectMake(0, 0, 1024, 655); 
_scrollView.contentOffset =offset; 
displayKeyboard = NO; 
} 

-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField { 
activeField = textField; 
return YES; 
} 

displayKeyboard, смещенные и activeField объявленные в файле .h.

Также помните, чтобы удалить уведомления в viewDidDisappear: анимированные

Хотя этот метод довольно сильно отличается, чем предыдущий один заявил, что это один не оставляет черную часть на вершине во время навигации между классами, когда uikeyboard активен ,

Также я заметил, что если я использовал устаревший UIKeyboardBoundsUserInfoKey, я использовал для получения правильной ширины и высоты клавиатуры (я работаю только в ландшафтном режиме). В то время как когда я использовал UIKeyboardFrameBeginUserInfoKey, значения ширины и высоты были взаимозаменяемы. Я все еще пытаюсь понять эту проблему.

Также, когда клавиатура появлялась, к ней было добавлено фиксированное пространство 49 пикселей. Я предположил, что это моя высота табло и поэтому вычитается 49.

 Смежные вопросы

  • Нет связанных вопросов^_^