I'm trying to create a "like" button in my project. To detect current row (where the clicked button is) in UITableViewCell i'm using the following code:
-(void)likeBtnClick:(id)sender {
UIButton *senderButton = (UIButton *)sender;
NSLog(@"current Row=%d",senderButton.tag);
}
So, for the first cell NSLog shows
"current Row=203", for the second – "current Row=200", for the third – "current Row=197". But for the 4th row it is "current Row=203" again (5th – "current Row=200", 6th – "current Row=197", etc)!
And the same error repeats every 3 rows.
My question is - how to get the right number of the current row in UITableView?
UPDATE:
For Lyndsey Scott – cellForRowAtIndexPath method code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NewsCell"];
}
[self.tableView setScrollsToTop:YES];
[HUD hide:YES];
Location *location = [_locations objectAtIndex:indexPath.row];
UIButton *lkbut = (UIButton*) [cell viewWithTag:300];
[lkbut setImage:[UIImage imageNamed:@"likehq2.png"] forState:UIControlStateNormal];
NSInteger value = [location.information intValue];
NSLog(@"val %ld", (long)value);
lkbut.tag = value;
NSLog(@"ur %@", location.user_like);
[lkbut addTarget:self action:@selector(likeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//...
return cell;
}
Solution:
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
NSLog(@"indexPath.row = %ld", (long)indexPath.row);
NSLog(@"%lu", (unsigned long)[_locations count] - (long)indexPath.row);
"(unsigned long)[_locations count]" - is a number of your rows. //everyone has own code here
Thanks Anna, Lyndsey Scott and JOM!