Reputation: 47348
I have one table view within the app that I hope multiple parts of the app would be able to use to post updates to the table view with possible actions that the user can take. One of the ways that I thought of implementing this is via a large enum, with a switch statement with the table view. In this case, the table view would be performing an action based on the enum value for the table cell. This requires knowledge of the classes involved, and seems overly complicated.
There has to be a better way. Is it possible to use selectors with a target for the UITableViewCell accessory button?
I think that for regular buttons and navbar buttons I can do something like this:
[thisIconBtn addTarget:self action:@selector(changeIconState:) forControlEvents:UIControlEventTouchUpInside];
is there an equivalent way of assigning an action to the UITableView accessory? Or should I stick with the large enum?
thank you!
Upvotes: 1
Views: 4479
Reputation: 52738
Unfortunately, the accessoryAction
of a UITableViewCell
is deprecated as of iOS 3.0.
From the UITableViewCell Reference Docs:
accessoryAction
The selector defining the action message to invoke when users tap the accessory view. (Deprecated in iOS 3.0. Instead use thetableView:accessoryButtonTappedForRowWithIndexPath:
for handling taps on cells.)
However, if your accessory view inherits from UIControl
(UIButton
, etc), you may set a target and action through the addTarget:action:forControlEvents:
method.
Something like this (modify to fit your needs):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
}
// Set the accessoryType to None because we are using a custom accessoryView
cell.accessoryType = UITableViewCellAccessoryNone;
// Assign a UIButton to the accessoryView cell property
cell.accessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
// Set a target and selector for the accessoryView UIControlEventTouchUpInside
[(UIButton *)cell.accessoryView addTarget:self action:@selector(someAction:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
Or, the more traditional route (I'm not positive, but I believe your question states that this is what you are trying to avoid. You can ignore this block of code if that is true.):
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.section) {
case 0:
switch (indexPath.row) {
case 0:
// <statements>
break;
case 1:
// <statements>
break;
default:
// <statements>
break;
}
break;
case 1:
switch (indexPath.row) {
case 0:
// <statements>
break;
case 1:
// <statements>
break;
default:
// <statements>
break;
}
break;
default:
break;
}
}
Upvotes: 6