按下按鈕獲取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決定改變視圖結構,那么所有其他答案都可能會破裂。
慕哥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;
慕后森
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來實現相同的代碼。
- 3 回答
- 0 關注
- 529 瀏覽
添加回答
舉報
0/150
提交
取消
