How to pass an int value on UIButton click inside UITableView

Posted by Toran Billups on Stack Overflow See other posts from Stack Overflow or by Toran Billups
Published on 2010-12-31T14:43:12Z Indexed on 2010/12/31 14:53 UTC
Read the original article Hit count: 195

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 
}

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c