2012-10-03 2 views
1

Я разрабатываю приложение с 15 текстовыми полями. Я использовал UIScrollView, чтобы сделать прокрутку возможной. Но мои последние пять текстовых полей скрываются за клавиатурой, когда вы нажимаете на эти текстовые поля для редактирования. Как переместить эти текстовые поля над клавиатурой, когда они находятся в режиме редактирования? Опять же, текстовые поля находятся в UIScrollView. Не UIView.Клавиатура скрывает текстовые поля в UIScrollView. Как переместить текстовое поле в соответствии с клавиатурой?

+0

Ничего не работает для UIScrollView, вот почему я разместил вопрос – dcprog

+0

возможный дубликат [Как сделать UITextField движением вверх, когда присутствует клавиатура] (http://stackoverflow.com/questions/1126726/how-to-make- a-uitextfield-move-up-when-keyboard-is-present) –

ответ

0

Вы должны соответствующим образом настроить contentSize и contentOffset на свой scrollView. Поэтому, если ваше последнее текстовое поле находится в начале (0,300), вы, вероятно, захотите, чтобы ваш contentSize был CGSizeMake (0, 600) или около того, а затем установите для contentOffset значение (0, 250).

+0

Могу ли я узнать код? Я имею в виду, я пробовал все CGSizeMake до сих пор – dcprog

2

Пробег: TPKeyboardAvoidingScrollView.

Просто возьмите вид прокрутки, который у вас уже есть, и измените его класс на TPKeyboardAvoidingScrollView, теперь, когда клавиатура всплывает, он будет регулировать размер и смещение, чтобы поля были правильно отображены.

Я рекомендую это, потому что, когда у вас сложная компоновка (много текстовых полей и других компонентов), это может быть сложно сделать это вручную. Этот контроль так же прост, как и получается, и работает как шарм!

0

Вы можете уменьшить ваш scrollViewY координату в textFieldShouldBeginEditing:

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField 
{ 
    if(textField == textField11 || textField == textField12 || textField == textField13 || textField == textField14 || textField == textField15) 
    { 
     [UIView beginAnimations:nil context:NULL]; 
     [UIView setAnimationDuration:0.3]; 
     //set Y according to keyBoard height 
     [scrollView setFrame:CGRectMake(0.0,-220.0,320.0,460.0)]; 
     [UIView commitAnimations]; 
    } 
} 

и установить scrollView кадр, как это было при нажатии возврата ключа клавиатуры

-(BOOL)textFieldShouldReturn:(UITextField *)textField 
{ 
    [textField resignFirstResponder]; 
    [UIView beginAnimations:nil context:NULL]; 
    [UIView setAnimationDuration:0.3]; 
    [scrollView setFrame:CGRectMake(0.0,0.0,320.0,460.0)]; 
    [UIView commitAnimations]; 
} 
+0

что вы сравниваете в if (textField == textField11 || textField == textField12 || textField == textField13)? – dcprog

+0

это ваши последние пять 'textField', которые вы сказали, что это 15, поэтому я считаю их 11,12,13,14,15. – TheTiger

+0

nope ... его не работает – dcprog

1

Вот некоторые примеры кода :

#define kOFFSET_FOR_KEYBOARD 80.0 

-(void)keyboardWillShow { 
    // Animate the current view out of the way 
    if (self.view.frame.origin.y >= 0) 
    { 
     [self setViewMovedUp:YES]; 
    } 
    else if (self.view.frame.origin.y < 0) 
    { 
     [self setViewMovedUp:NO]; 
    } 
} 

-(void)keyboardWillHide { 
    if (self.view.frame.origin.y >= 0) 
    { 
     [self setViewMovedUp:YES]; 
    } 
    else if (self.view.frame.origin.y < 0) 
    { 
     [self setViewMovedUp:NO]; 
    } 
} 

-(void)textFieldDidBeginEditing:(UITextField *)sender 
{ 
    if ([sender isEqual:mailTf]) 
    { 
     //move the main view, so that the keyboard does not hide it. 
     if (self.view.frame.origin.y >= 0) 
     { 
      [self setViewMovedUp:YES]; 
     } 
    } 
} 

//method to move the view up/down whenever the keyboard is shown/dismissed 
-(void)setViewMovedUp:(BOOL)movedUp 
{ 
    [UIView beginAnimations:nil context:NULL]; 
    [UIView setAnimationDuration:0.3]; // if you want to slide up the view 

    CGRect rect = self.view.frame; 
    if (movedUp) 
    { 
     // 1. move the view's origin up so that the text field that will be hidden come above the keyboard 
     // 2. increase the size of the view so that the area behind the keyboard is covered up. 
     rect.origin.y -= kOFFSET_FOR_KEYBOARD; 
     rect.size.height += kOFFSET_FOR_KEYBOARD; 
    } 
    else 
    { 
     // revert back to the normal state. 
     rect.origin.y += kOFFSET_FOR_KEYBOARD; 
     rect.size.height -= kOFFSET_FOR_KEYBOARD; 
    } 
    self.view.frame = rect; 

    [UIView commitAnimations]; 
} 


- (void)viewWillAppear:(BOOL)animated 
{ 
    // register for keyboard notifications 
    [[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardWillShow) 
              name:UIKeyboardWillShowNotification 
              object:nil]; 

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

- (void)viewWillDisappear:(BOOL)animated 
{ 
    // unregister for keyboard notifications while not visible. 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
              name:UIKeyboardWillShowNotification 
              object:nil]; 

    [[NSNotificationCenter defaultCenter] removeObserver:self 
              name:UIKeyboardWillHideNotification 
              object:nil]; 
} 
Смежные вопросы