Reputation: 103
I have a UITableView where I want the user to be able to click two buttons, in the header of the section, one for adding a new record, and the other one for editing them, so I first tried using tableView viewForHeaderInSection
and tableView heightForHeaderInSection
like this:
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 44;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView* v = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 360, 44)];
UIToolbar* tb = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 360, 44)];
UIBarButtonItem* spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem* addBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(onAddVehicleInterest:)];
UIBarButtonItem* editBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(onEditVehiclesInterest:)];
[tb setItems:[NSArray arrayWithObjects:spacer, addBtn, editBtn, nil]];
[v addSubview:tb];
return v;
}
- (IBAction)onAddVehicleInterest: (id) sender {
NSLog(@"Add");
}
- (IBAction)onEditVehiclesInterest:(id)sender {
NSLog(@"Edit");
}
When I run the app, I can see the three UIBarButtonItems correctly, and I can click them, but the NSLog line is never called. So I added a UIToolbar
directly in the nib file, added the 3 UIBarButtonItem
controls to it, and tied the onAddVehicleInterest
and onEditVehiclesInterest
to the respective buttons. But that doesn't work either...
So, as a last test, I added a UIButton
to the nib and tied its Touch Up Inside event to one of the methods, and that works as expected. So I'm confused. What am I doing wrong?
Upvotes: 3
Views: 3700
Reputation: 7031
I had a UITapGestureRecognizer on the parent view of the view controller. Once I removed the tap gesture, my UIBarButtonItems began to respond properly to all selectors.
Upvotes: 5
Reputation: 38249
Try this:
UIBarButtonItem* addBtn;
if([self respondsToSelector:@selector(onAddVehicleInterest:)])
{
addBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(onAddVehicleInterest:)];
}
UIBarButtonItem* editBtn
if([self respondsToSelector:@selector(onEditVehiclesInterest:)])
{
editBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(onEditVehiclesInterest:)];
}
if(addBtn && editBtn)
{
[tb setItems:[NSArray arrayWithObjects:spacer, addBtn, editBtn, nil]];
}
Upvotes: 0
Reputation: 11314
I have also faced the same problem and I get it solved by changing:-
- (IBAction)onAddVehicleInterest: (id) sender {
to
- (IBAction)onAddVehicleInterest: (UIBarButtonItem *) sender {
I also dont know why it was not working earlier, but my problem solved with it. You can try this.
Upvotes: 1