Graphics Programs Reference
In-Depth Information
A bar button item has a target-action pair that works like UIControl 's target-action
mechanism: when tapped, it sends the action message to the target. When you set a target-
action pair in a XIB file, you Control-drag from a button to its target and then select a
method from the list of IBAction s. To programmatically set up a target-action pair, you
pass the target and the action to the button.
In ItemsViewController.m , create a UIBarButtonItem instance and give it its
target and action.
- (id)init
{
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
UINavigationItem *n = [self navigationItem];
[n setTitle:@"Homepwner"];
// Create a new bar button item that will send
// addNewItem: to ItemsViewController
UIBarButtonItem *bbi = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(addNewItem:)];
// Set this bar button item as the right item in the navigationItem
[[self navigationItem] setRightBarButtonItem:bbi];
}
return self;
}
The action is passed as a value of type SEL . Recall that the SEL data type is a pointer to a
selector and that a selector is the entire message name including any colons. Note that
@selector() doesn't care about the return type, argument types, or names of argu-
ments. Also, remember that @selector() doesn't check to see if the method actually
exists. If you give a SEL to a button, that button will send the corresponding message re-
gardless of whether the method is implemented by the target.
Build and run the application. Tap the + button, and a new row will appear in the table.
(Note that this is not the only way to set up a bar button item; check the documentation for
other initialization messages you can send an instance of UIBarButtonItem .)
Now let's add another UIBarButtonItem to replace the Edit button in the table view
header. In ItemsViewController.m , edit the init method.
- (id)init
{
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
UINavigationItem *n = [self navigationItem];
Search WWH ::




Custom Search