Панель инструментов сверху клавиатуры с первым ответчиком - PullRequest
1 голос
/ 02 июля 2010

Это довольно распространенная тема, и на нее есть много ответов.

Ситуация : у меня полноэкранный (без панели инструментов) UITextView с UIToolbar внизу. когда UITextView получает первый респондент, я хочу, чтобы панель инструментов сдвинулась вверх с помощью клавиатуры, и добавила кнопку «Готово», которая отключит клавиатуру.

Пока : у меня это полностью работает, основываясь на этом примере . За исключением того факта, что когда я помещаю [textView becomeFirstResponder]; в свой viewDidLoad, панель инструментов не анимируется. Даже если keyboardWillShow называется. У кого-нибудь есть идеи?

Код : просто вам не нужно проверять пример кода, вот что происходит:

В ViewDidLoad:

- (void)viewDidLoad {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
   [nc addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
   [nc addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
   [textView becomeFirstResponder];
       [super viewDidLoad];
}

В клавиатуре WillShow:

- (void)keyboardWillShow:(NSNotification *)notification {
NSLog(@"keyboard will show");
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationCurve:[[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
    [UIView setAnimationDuration:[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];

    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                                                                            target:self 
                                                                            action:@selector(keyboardDone)];
    NSMutableArray *toolbarItems = [NSMutableArray arrayWithArray:[toolbar items]];
    [toolbarItems addObject:doneButton];
    [toolbar setItems:toolbarItems];

    CGRect frame = self.view.frame;
    frame.size.height -= [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size.height;
    self.view.frame = frame;
     [UIView commitAnimations];
 }

Ответы [ 2 ]

3 голосов
/ 02 июля 2010

Попробуйте перевести вызов -becomeFirstResponder на -viewWillAppear:animated: или -viewDidAppear:animated:.Я думаю, что -viewDidLoad обычно вызывается непосредственно перед тем, как представление фактически добавляется в иерархию представления.

0 голосов
/ 28 ноября 2012

Добавьте это в свой код

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    return YES;
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{

    UIToolbar* keyboardDoneButtonView   = [[UIToolbar alloc] init];
    keyboardDoneButtonView.barStyle     = UIBarStyleBlack;
    keyboardDoneButtonView.translucent  = YES;
    keyboardDoneButtonView.tintColor    = nil;
    [keyboardDoneButtonView sizeToFit];

    UIBarButtonItem* doneButton    = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered  target:self action:@selector(doneBtnTapped:)];

    // I put the spacers in to push the doneButton to the right side of the picker view
    UIBarButtonItem *spacer1    = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
                                                                                target:nil action:nil];

    // I put the spacers in to push the doneButton to the right side of the picker view
    UIBarButtonItem *spacer    = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
                                                                               target:nil action:nil];

    [keyboardDoneButtonView setItems:[NSArray arrayWithObjects:spacer, spacer1, doneButton, nil]];

    // Plug the keyboardDoneButtonView into the text field...
    textView.inputAccessoryView = keyboardDoneButtonView;

    return YES;
}

- (void)doneBtnTapped:(id)sender {
     [yourTextView resignFirstResponder];
}

И все готово ...

...