【发布时间】:2023-04-05 23:26:02
【问题描述】:
我有一个 NSArray 和一个带有一些按钮的 tableView,它们的标题是当前 indexpath 行的数组中的字符串
- (CustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexpath {
_selectedRow = indexpath.row;
static NSString *simpleTableIdentifier = @"customCell";
cell = [myTableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
[cell.playButton setTitle:array[indexpath.row] forState: UIControlStateNormal];
return cell;
}
按钮标题显示得很好。
现在我有一些mp3文件,名字和数组中的字符串一样,我想播放所选单元格对应的文件。
fileToPlay = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@", array[_selectedRow]]; ofType:@"mp3"];
这里发生的情况是,播放的文件始终是对应于表格中最后一个可见单元格的文件。
我也有
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexpath {
_selectedRow = indexpath.row;
}
但如果我尝试在此处打印 _selectedRow,则日志中不会出现任何内容。
当我点击表格中的一个单元格时,它似乎没有被选中(它不是灰色的)。
dataSource 和 delegate 也很好地连接到 tableview。
更新
我发现如果我点击按钮,就好像我没有点击选定的行。如果我单击单元格(按钮外),则 indexPath.row 是正确的。
【问题讨论】:
-
试试这个:将 myGestureRecognizer.cancelsTouchInView 设置为 false
-
为什么要添加 _selectedRow = indexpath.row;在 cellForRowAtIndex 中?
-
您确定
didSelectRowAtIndexPath在您选择单元格时会被调用吗?它可能根本没有被选中,这将使您的_selectedRow作为最后一个加载的单元格(如果您向下滚动,则为底部,如果您向上滚动,则为顶部...)。 -
更好的选择你可以在按钮单击 [cell.playButton setTag:indexPath.row] 上使用这样的方法; [cell.playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
-
我发现如果我点击按钮,就好像我没有点击选定的行。如果我单击单元格(按钮外),则 indexPath.row 是正确的。
标签: ios objective-c uitableview tableviewcell didselectrowatindexpath