Добавление UIToolbar в представление дополнительных устройств ввода в некоторые текстовые поля

В моих поисках своего первого приложения для iPhone я опубликовал информацию о правильном способе обработки клавиши возврата на клавиатуре iOS. Теперь мне нужно разобраться с панелью инструментов над клавиатурой с кнопками prev / next и done. Я работал с примером со следующего сайта: Представление аксессуаров ввода

Пример работает, но я хочу использовать UIToolbar и UIBarButtonItem вместо обычного представления с кнопками. Пробовал разные комбинации, пока ни одна не работает. Вот что у меня есть на данный момент.

Заголовок:

#import 

@interface ViewController : UIViewController 
{
    UITextField* txtActiveField;
    UIToolbar* keyboardToolbar;
    UIBarButtonItem* btnDone;
    UIBarButtonItem* btnNext;
    UIBarButtonItem* btnPrev;
}

@property (nonatomic, strong) IBOutlet UITextField* firstNameTextField;
@property (nonatomic, strong) IBOutlet UITextField* lastNameTextField;
@property (nonatomic, strong) IBOutlet UITextField* cityTextField;

@property (nonatomic, strong) UITextField* txtActiveField;
@property (nonatomic, strong) UIToolbar* keyboardToolbar;
@property (nonatomic, strong) UIBarButtonItem* btnDone;
@property (nonatomic, strong) UIBarButtonItem* btnNext;
@property (nonatomic, strong) UIBarButtonItem* btnPrev;

-(void)createInputAccessoryView;

@end

Источник:

#import "ViewController.h"

@implementation ViewController

@synthesize firstNameTextField = _firstNameTextField;
@synthesize lastNameTextField = _lastNameTextField;
@synthesize cityTextField = _cityTextField;

@synthesize txtActiveField = _txtActiveField;
@synthesize keyboardToolbar = _keyboardToolbar;
@synthesize btnDone = _btnDone;
@synthesize btnNext = _btnNext;
@synthesize btnPrev = _btnPrev;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self createInputAccessoryView];
}

- (void)viewDidUnload
{
    [self setFirstNameTextField:nil];
    [self setLastNameTextField:nil];
    [self setCityTextField:nil];

    [self setTxtActiveField:nil];
    [self setKeyboardToolbar:nil];
    [self setBtnDone:nil];
    [self setBtnNext:nil];
    [self setBtnPrev:nil];

    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

-(void)gotoPrevTextfield
{
    if (self.txtActiveField == self.firstNameTextField)
    {
        return;
    }
    else if (self.txtActiveField == self.lastNameTextField)
    {
        [self.firstNameTextField becomeFirstResponder];
    }
    else if (self.txtActiveField == self.cityTextField)
    {
        [self.lastNameTextField becomeFirstResponder];
    }           
}

-(void)gotoNextTextfield
{
    if (self.txtActiveField == self.firstNameTextField)
    {
        [self.lastNameTextField becomeFirstResponder];
    }
    else if (self.txtActiveField == self.lastNameTextField)
    {
        [self.cityTextField becomeFirstResponder];
    }
    else if (self.txtActiveField == self.cityTextField)
    {
        return;
    }           
}

-(void)doneTyping
{
    [self.txtActiveField resignFirstResponder];
}

-(void)createInputAccessoryView
{
    self.keyboardToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
    self.keyboardToolbar.barStyle = UIBarStyleBlackTranslucent;
    self.keyboardToolbar.tintColor = [UIColor darkGrayColor];

    btnPrev = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:@selector(gotoPrevTextfield:)];
    btnNext = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:@selector(gotoNextTextfield:)];
    btnDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneTyping:)];

    [self.keyboardToolbar addSubview:(UIView*)btnPrev];
    [self.keyboardToolbar addSubview:(UIView*)btnNext];
    [self.keyboardToolbar addSubview:(UIView*)btnDone];

    [self.firstNameTextField setInputAccessoryView:self.keyboardToolbar];
    [self.lastNameTextField setInputAccessoryView:self.keyboardToolbar];
    [self.cityTextField setInputAccessoryView:self.keyboardToolbar];
}

-(void)textFieldDidBeginEditing:(UITextField*)textField
{
    self.txtActiveField = textField;
}
@end

Когда я запускаю приложение, я получаю:

012-01-21 09:31:19.798 KeyboardToolbar[14772:f803] -[UIBarButtonItem superview]: unrecognized selector sent to instance 0x6b19350
2012-01-21 09:31:19.799 KeyboardToolbar[14772:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIBarButtonItem superview]: unrecognized selector sent to instance 0x6b19350'
*** First throw call stack:
(0x13bc052 0x154dd0a 0x13bdced 0x1322f00 0x1322ce2 0x5042f 0x4a72b 0x3422 0x2a58 0xd964e 0x39a73 0x39ce2 0x39ea8 0x40d9a 0x11be6 0x128a6 0x21743 0x221f8 0x15aa9 0x12a6fa9 0x13901c5 0x12f5022 0x12f390a 0x12f2db4 0x12f2ccb 0x122a7 0x13a9b 0x2728 0x2685 0x1)
terminate called throwing an exception

Я предполагаю, что я неправильно выделил один из элементов. Мне также интересно, нужны ли мне поля в классе для кнопок или их можно просто добавить на панель инструментов. И я помещаю строку в заголовок, чтобы мне не приходилось ставить все свои методы в начало файла. Еще не знаю синтаксиса для пересылки объявления метода, как вы могли бы сделать в C.

Спасибо.

Обновление:

Итак, я внес некоторые изменения в createInputAccessoryView. Сейчас я использую addItems для добавления кнопок. Я сделал переменные кнопки локальными (но у меня была та же проблема, когда они были, как и раньше). Хорошая новость в том, что приложение больше не вылетает, плохая новость в том, что панель инструментов отображается, но без кнопок. Не уверен, что еще мне нужно сделать, чтобы кнопки действительно отображались.Все примеры, которые я видел, похожи.

-(void)createInputAccessoryView
{
    self.keyboardToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
    self.keyboardToolbar.barStyle = UIBarStyleBlackTranslucent;
    self.keyboardToolbar.tintColor = [UIColor darkGrayColor];

    UIBarButtonItem* previousButton = [[UIBarButtonItem alloc] initWithTitle:@"Previous" style:UIBarButtonItemStyleBordered target:self action:@selector(gotoPrevTextfield)];
    UIBarButtonItem* nextButton = [[UIBarButtonItem alloc] initWithTitle:@"Next" style:UIBarButtonItemStyleBordered target:self action:@selector(gotoNextTextfield)];
    UIBarButtonItem* flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneTyping:)];

    [keyboardToolbar setItems:[NSArray arrayWithObjects: previousButton, nextButton, flexSpace, doneButton, nil] animated:NO];

    [self.firstNameTextField setInputAccessoryView:self.keyboardToolbar];
    [self.lastNameTextField setInputAccessoryView:self.keyboardToolbar];
    [self.cityTextField setInputAccessoryView:self.keyboardToolbar];
}

9
задан Tyrel Van Niekerk 22 January 2012 в 15:36
поделиться