So I have a view controller with a single UITableView that shows a string to the user. But I needed a way to have the user select this object by id using a normal UIButton so I added it as a subview and the click event works as expected.
The issue is this – how can I pass an int value to this click event? I’ve tried using attributes of the button like button.tag or button.accessibilityhint without much success. How do the professionals pass an int value like this?
Also it’s important that I can get the actual [x intValue] from the int later in the process. A while back I thought I could do this with a simple
NSLog(@”the actual selected hat was %d”, [obj.idValue intValue]);
But this doesn’t appear to work (any idea how I can pull the actual int value directly from the variable?).
The working code I have is below
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if ([self.hats count] > 0) {
Hat* obj = [self.hats objectAtIndex: [indexPath row]];
NSMutableString* fullName = [[NSMutableString alloc] init];
[fullName appendFormat:@"%@", obj.name];
[fullName appendFormat:@" %@", obj.type];
cell.textLabel.text = fullName;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
//add the button to subview hack
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(50, 5, 50, 25);
[button setTitle:@"Select" forState:UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
button.adjustsImageWhenHighlighted = YES;
button.tag = obj.idValue; //this is my current hack to add the id but no dice :(
[button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
//hack
}
return cell;
}
- (void)action:(id)sender {
int* hatId = ((UIButton *)sender).tag; //try to pull the id value I added above ...
//do something w/ the hatId
}
The final solution consisted of a few changes:
1.) Instead of using type int I switched to NSNumber (thanks to a few of the comments made)
also I found int to be more of a problem when it comes to memory management because I’m new 🙁
2.) Instead of setting the tag to an id I used some concepts mentioned in the comments and pushed the entire object to get more detail about it when I pulled it from action later.
Here is the revised method where I set the object
And here is the revised action where I pull out the object, then any property I want
One last comment about the button reuse mentioned – I’m yet to find a running problem with this but I am interested in another solution that would still allow me to have a custom button in each table cell.