Wednesday, December 29, 2010

Adding a toolbar to keyboard for textField and textView

textField and textView have a property inputAccessoryView which allows you to easily add a toolbar to the top of the keyboard to show your custom buttons.

- (IBAction)beginEditing: (id)sender {
CGFloat _width = self.view.frame.size.width;
CGFloat _height = 40.0;

// Create a new toolbar
UIToolbar *toolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, -_height, _width, _height)] autorelease];
// Create the necessary buttons
UIBarButtonItem *barButtonItemSubmit = [[[UIBarButtonItem alloc] initWithTitle:@"Submit" style:UIBarButtonItemStyleBordered target:self action:@selector(btnSubmitClicked:)] autorelease];
UIBarButtonItem *barButtonItemCancel = [[[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(btnCancelClicked:)] autorelease];
/*
By default the buttons that are added to the toolbar are left aligned.
To align them as you like, create a flexible space bar button and add it where you want.
*/
UIBarButtonItem *flexibleSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
/*
Adding the flexible space in between will make both buttons float towards the opposite ends.
You can repeat the flexible space as many times and at positions to get the desired layout of buttons.
*/
[toolbar setItems:[[[NSArray alloc] initWithObjects:barButtonItemSubmit, flexibleSpace, barButtonItemCancel, nil] autorelease]];

if ([sender isEqual:myTextField]) {
myTextField.inputAccessoryView = toolbar;
}
else if ([sender isEqual:myTextView]) {
myTextView.inputAccessoryView = toolbar;
}
}


Assign the begin editing event of the text field to the above function.

For textview, you might need to do something like this:
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
if ([textView isEqual:myTextView]) {
[self beginEditing:myTextView];
}
return YES;
}

No comments:

Why Your New External Drive is Breaking Your macOS Builds

Picture this: you're running dangerously low on disk space, so you invest in a brand new external drive. Time to migrate your developmen...