Peter
Peter

Reputation: 193

How to send sender inside action of UIBarButtonItem inside a UIToolbar

Seems like an easy task. A button inside a toolbar (on top of a keyboard) should send the sender to a function. With the code below I receive "unrecognized selector sent to instance" in the debugger.

My goal is to access a specific TextField of a custom cell. This code worked pretty well for identifying e.g. a switch

Declaration of the ToolBar:

UIToolbar* itemToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
itemToolbar.barStyle = UIBarStyleBlackTranslucent;
itemToolbar.items = [NSArray arrayWithObjects:
                     [[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelNumberPad)],
                     [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                     [[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)],
                     nil];
[itemToolbar sizeToFit];

Function of doneWithNumberPad:

- (void)doneWithNumberPad:(id)sender {
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
    NSLog(@"%@", [object valueForKey:@"item"]);
}

Thanks for any help

Upvotes: 3

Views: 3404

Answers (1)

Anupdas
Anupdas

Reputation: 10201

You just need to include colon in your selector method for save button

itemToolbar.items = [NSArray arrayWithObjects:
                     [[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelNumberPad)],
                     [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                     [[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:)],
                     nil];

sender has type of NSObject, convert it to UIBarButtonItem before converting point.

- (void)doneWithNumberPad:(id)sender {
    UIBarButtonItem *button = (UIBarButtonItem *)sender;
    CGPoint buttonPosition = [button convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
    NSLog(@"%@", [object valueForKey:@"item"]);
}

Upvotes: 5

Related Questions