亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

按下按鈕獲取UITableView單元格行

按下按鈕獲取UITableView單元格行

慕虎7371278 2019-08-16 14:43:29
按下按鈕獲取UITableView單元格行我有一個tableview控制器,顯示一行單元格。每個單元格有3個按鈕。我已將每個單元格的標簽編號為1,2,3。問題是我不知道如何找到按下按鈕的單元格。我當前只在按下其中一個按鈕時才收到發件人的標簽。當按下按鈕時,有沒有辦法獲取單元格行號?
查看完整描述

3 回答

?
萬千封印

TA貢獻1891條經驗 獲得超3個贊

你應該真的使用這種方法:

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根據按下的按鈕的位置給你。然后,cellForRowAtIndexPath如果您需要單元格或indexPath.row需要行號,則只需調用。

如果你是偏執狂,你可以if (indexPath) ...在使用它之前檢查,以防萬一indexPath在表格視圖中找不到該點。

如果Apple決定改變視圖結構,那么所有其他答案都可能會破裂。


查看完整回答
反對 回復 2019-08-16
?
慕哥9229398

TA貢獻1877條經驗 獲得超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;


查看完整回答
反對 回復 2019-08-16
?
慕后森

TA貢獻1802條經驗 獲得超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來實現相同的代碼。


查看完整回答
反對 回復 2019-08-16
  • 3 回答
  • 0 關注
  • 529 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號