Silver Challange


#1

I have done it with a UIToolbar placed just above the keyboard with a single UIBarButtonItem named “Done”.

First, I’ve placed a UIToolbar to BNRDetailViewController.xib.

Then, in BNRDetailViewController.m, I’ve added a property for UIToolbar at the class extension and made all the connections necessary in the IB.

@interface ItemDetailViewController ()

@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *serialNumberField;
@property (weak, nonatomic) IBOutlet UITextField *valueField;
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;
@property (weak, nonatomic) IBOutlet UIToolbar *toolbar;

@end

I overrode viewDidLoad to hide the toolbar when the view is loaded.

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.toolbar.hidden = YES;
}

Next, I overrode textFieldDidBeginEditing: so that when valueField is active toolbar will be present. While at it, I laid its UIBarButtonItems, 3 of them being empty spaces and the last one is the “Done” button.

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.valueField) {
        self.toolbar.hidden = NO;
        UIBarButtonItem* flexSpace1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        UIBarButtonItem* flexSpace2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        UIBarButtonItem* flexSpace3 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneEditing)];
        
        [self.toolbar setItems:[NSArray arrayWithObjects: flexSpace1, flexSpace2, flexSpace3, doneButton, nil] animated:NO];
        
    }
}

When “Done” button is pressed, it sends a doneEditing message and valueField will resignFirstResponder.

- (void)doneEditing
{
    [self.valueField resignFirstResponder];
}

I am fairly new at this so any feedback is welcome.

Thanks.