按下按鈕獲取UITableView單元格行我有一個tableview控制器,顯示一行單元格。每個單元格有3個按鈕。我已將每個單元格的標(biāo)簽編號為1,2,3。問題是我不知道如何找到按下按鈕的單元格。我當(dāng)前只在按下其中一個按鈕時才收到發(fā)件人的標(biāo)簽。當(dāng)按下按鈕時,有沒有辦法獲取單元格行號?
3 回答

萬千封印
TA貢獻1891條經(jīng)驗 獲得超3個贊
你應(yīng)該真的使用這種方法:
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
Swift版本:
let buttonPosition = sender.convert(CGPoint(), to:tableView)let indexPath = tableView.indexPathForRow(at:buttonPosition)
這將indexPath
根據(jù)按下的按鈕的位置給你。然后,cellForRowAtIndexPath
如果您需要單元格或indexPath.row
需要行號,則只需調(diào)用。
如果你是偏執(zhí)狂,你可以if (indexPath) ...
在使用它之前檢查,以防萬一indexPath
在表格視圖中找不到該點。
如果Apple決定改變視圖結(jié)構(gòu),那么所有其他答案都可能會破裂。

慕哥9229398
TA貢獻1877條經(jīng)驗 獲得超6個贊
試試這個:
-(void)button1Tapped:(id)sender{ UIButton *senderButton = (UIButton *)sender; UITableViewCell *buttonCell = (UITableViewCell *)[senderButton superview]; UITableView* table = (UITableView *)[buttonCell superview]; NSIndexPath* pathOfTheCell = [table indexPathForCell:buttonCell]; NSInteger rowOfTheCell = [pathOfTheCell row]; NSLog(@"rowofthecell %d", rowOfTheCell);}
編輯:如果您使用的是contentView,請將其用于buttonCell:
UITableViewCell *buttonCell = (UITableViewCell *)senderButton.superview.superview;

慕后森
TA貢獻1802條經(jīng)驗 獲得超5個贊
我建議這種方式來獲取具有任何自定義子視圖的單元格的indexPath - (與iOS 7兼容以及所有以前的版本)
-(void)button1Tapped:(id)sender {//- (void)cellSubviewTapped:(UIGestureRecognizer *)gestureRecognizer {// UIView *parentCell = gestureRecognizer.view.superview; UIView *parentCell = sender.superview; while (![parentCell isKindOfClass:[UITableViewCell class]]) { // iOS 7 onwards the table cell hierachy has changed. parentCell = parentCell.superview; } UIView *parentView = parentCell.superview; while (![parentView isKindOfClass:[UITableView class]]) { // iOS 7 onwards the table cell hierachy has changed. parentView = parentView.superview; } UITableView *tableView = (UITableView *)parentView; NSIndexPath *indexPath = [tableView indexPathForCell:(UITableViewCell *)parentCell]; NSLog(@"indexPath = %@", indexPath);}
這也不需要self.tablview
。
另外,請注意注釋代碼,如果您希望通過添加到自定義子視圖的UIGestureRecognizer的@selector來實現(xiàn)相同的代碼。
- 3 回答
- 0 關(guān)注
- 521 瀏覽
添加回答
舉報
0/150
提交
取消