【发布时间】:2014-10-02 20:34:02
【问题描述】:
我正在尝试在我的项目中创建一个“喜欢”按钮。要检测 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!
【问题讨论】:
-
查看stackoverflow.com/a/1802875/467105 以获得比标签更好的方法。
-
我看过,但是像“0x00000016”这样的数字不是我需要的
-
您如何看待该文本?您如何记录生成的 indexPath?你试过
NSLog(@"indexPath.row = %d", indexPath.row);吗? -
您能否从您设置标签的 cellForRowAtIndexPath 方法中发布代码?
-
"-(void)likeBtnClick:(id)sender" 不在 "-(UITableViewCell *)tableView" 中,所以 indexPath 没有在那里声明...
标签: ios objective-c xcode uitableview