NSIndexPath返回nil

时间:2015-10-28 07:17:42

标签: ios uitableview nsindexpath

我有UIViewController的表格视图。表行包含触发操作的按钮。

//This is my button selector inside tableview delegate cellForRowAtIndexPath

[myBtn addTarget:self action:@selector(onButtonPress:event:)forControlEvents:UIControlEventTouchUpInside];

//This is button action



 -(void)onButtonPress:(UIButton*)sender {
       CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.myTableView];
       NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:buttonPosition];

       DestinationViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"DestinationViewController"];
       controller.args=myArgs;
       [self.navigationController pushViewController:controller animated:YES];


 }

//this is my back button action

- (IBAction)onBackPressed:(id)sender {
     [self.navigationController popViewControllerAnimated:YES];
}

第一次一切正常但我导航到其他ViewController并返回到tableview控制器后按回按钮再次点击表格行按钮NSIndexPath为零

我试过这个indexPathForRowAtPoint returns nil only for first cell in a uitableview

5 个答案:

答案 0 :(得分:0)

如果我理解你是正确的,那么你在TableViewCells中有按钮,当你点击其中一个按钮时,你就不会得到IndexPath。

当然没有IndexPath,因为你从未点过一个单元格。基本上你忽略了完整的tableview机制。

创建tableviewcell时,使用索引标记按钮。不是最好的方法,但会做。

答案 1 :(得分:0)

将按钮的标记设置为indexPath.row,并从标记中找到NSIndexPath。

myBtn.tag=indexPath.row;
[myBtn addTarget:self action:@selector(onButtonPress:)forControlEvents:UIControlEventTouchUpInside];

-(void)onButtonPress:(UIButton*)sender {

UIButton *btnSender =(UIButton *)sender;

 NSIndexPath *indexPath = [NSIndexPath indexPathForRow:btnSender.tag inSection:0];

}

答案 2 :(得分:0)

我不会使用方法indexPathForRowAtPoint:来获取indexPath。您可以使用其他方式对其进行归档。首先添加UIView类别:

标题文件:

#import <UIKit/UIKit.h>

@interface UIView (TableCell)

-(UITableViewCell*)getTableCell;

@end

和实施

@implementation UIView (TableCell)

-(UITableViewCell *)getTableCell
{
   while (self.superview) {
      if ([self.superview isKindOfClass:[UITableViewCell class]]) {
         return (UITableViewCell*)self.superview;
      }else {
         return [self.superview getTableCell];
      }
   }
   return nil;
}

现在,在您的onButtonPress:中,您可以这样做:

UITableViewCell *cell = [sender getTableCell];
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]

答案 3 :(得分:0)

我的建议你可以在&#39; viewWillAppear&#39 ;;下编写[tableView reload]。 或者使用其他方式来阻止实施

答案 4 :(得分:0)

尝试将委托发送到nextviewcontroller,如

   DestinationViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"DestinationViewController"];
   controller.args=myArgs;
   controller.delegate = self;
   [self.navigationController pushViewController:controller animated:YES];

当从viewController遍历到当前表时viewcontroller传递该委托。

这可能对你有所帮助......