我试图创建一个"喜欢"我的项目中的按钮。要使用以下代码检测UITableViewCell中的当前行(单击按钮所在的位置),请执行以下操作:
-(void)likeBtnClick:(id)sender {
UIButton *senderButton = (UIButton *)sender;
NSLog(@"current Row=%d",senderButton.tag);
}
因此,对于第一个单元格NSLog显示
"当前行= 203",对于第二个 - "当前行= 200",对于第三个 - "当前行= 197"。 但第4行是"当前行= 203" 再次(第5 - "当前行= 200",第6 - "当前行= 197"等)!
同样的错误每3行重复一次。
我的问题是 - 如何在UITableView中获取当前行的正确数字?
更新
对于Lyndsey Scott - cellForRowAtIndexPath方法代码:
- (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;
}
解决方案:
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]" - 是你的一些行。 //每个人都有自己的代码
感谢Anna,Lyndsey Scott和JOM!
答案 0 :(得分:1)
再次获得相同数字的原因是tableview单元格正在被回收。在你的情况下,似乎每次屏幕上最多有3行。
无论如何,这是我之前对类似问题的回答:iPhone - How to determine in which cell a button was pressed in a custom UITableViewCell
更新:安娜有一个很好的建议,也应该有效。请检查一下,看看它是否更好。
第三种方式可能是您在创建/回收单元格时使用indexPath.row重置单元格标记。总是有不止一种方法可以做任何事情;)
答案 1 :(得分:0)
我建议:
首先:
[lkbut addTarget:self action:@selector(likeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
应该是:
[lkbut addTarget:self action:@selector(likeBtnClick:andEvent:) forControlEvents:UIControlEventTouchUpInside];
并且您的button
操作方法应为:
-(void)likeBtnClick:(id)sender andEvent:(UIEvent*)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
NSLog(@"current Row=%d",indexPath.row);
}
基本上,不需要经历所有标签粘贴。