Reputation: 169
I'm attempting to implement a suggestion in this post: Pass an argument to selector to pass an @selector
argument to a UIButton
in a UITableViewCell
using objc_setAssociatedObject
and objc_getAssociatedObject
. The way I have it coded, it always ends up passing the row of whatever the last cell was that it created/loaded. Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *mainLabel;
soundButton=[UIButton buttonWithType:UIButtonTypeCustom];
if (cell == nil){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
soundButton.tag = 33;
[soundButton addTarget:self action:@selector(soundButtonAction) forControlEvents:UIControlEventTouchUpInside];
[soundButton setFrame:CGRectMake(210,3,68, 37)];
[soundButton setBackgroundImage:[UIImage imageNamed:@"musicNote"] forState:UIControlStateNormal];
[cell.contentView addSubview:soundButton];
} else {
soundButton = (UIButton *)[cell.contentView viewWithTag:33];
}
objc_setAssociatedObject(soundButton, "IndexPath", indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return cell;
}
-(void)soundButtonAction
{
NSIndexPath *ip = objc_getAssociatedObject(soundButton, "IndexPath");
Upvotes: 1
Views: 480
Reputation: 46578
looks like soundButton
is an ivar in your class? it is get override every time a cell is requested so you only get the last one.
also I think it is not good idea to use "IndexPath"
as the key.
static char indexPathKey; // use address of indexPathKey as key
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *mainLabel;
soundButton=[UIButton buttonWithType:UIButtonTypeCustom];
if (cell == nil){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
soundButton.tag = 33;
[soundButton addTarget:self action:@selector(soundButtonAction:) /*extra :*/ forControlEvents:UIControlEventTouchUpInside];
[soundButton setFrame:CGRectMake(210,3,68, 37)];
[soundButton setBackgroundImage:[UIImage imageNamed:@"musicNote"] forState:UIControlStateNormal];
[cell.contentView addSubview:soundButton];
} else {
soundButton = (UIButton *)[cell.contentView viewWithTag:33];
}
objc_setAssociatedObject(soundButton, &indexPathKey, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return cell;
}
-(void)soundButtonAction:(UIButton *)sender
{
NSIndexPath *ip = objc_getAssociatedObject(sender, &indexPathKey);
Upvotes: 1