无法在UITableViewController中选择UITableView行

时间:2015-02-24 15:32:53

标签: ios objective-c iphone uitableview uiviewcontroller

我使用storyboard创建了一个应用。在其他屏幕中,我直接使用了UITableViewController,并且选择按预期工作。

在这种情况下,我有一个UITableView,它是UIViewController中的几个控件之一。

我的自定义ViewController.h文件的定义类似于以下内容:

@interface MyViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>
    @property (weak,nonatomic) IBOutlet UITableView *myTableView;
@end

然后在viewDidLoad内我这样做:

_myTableView.delegate = self;
_myTableView.dataSource = self;

完成此操作后,我的numberOfSectionsInTableViewnumberOfRowsInSectioncellForRowAtIndexPath方法都被调用,我的表格看起来就像我想要的那样。

我遇到的问题是行没有选择而且didSelectRowAtIndexPath方法没有被调用。

我已经检查了故事板视图中的选择设置为单一选择,我还尝试在_myTableView.allowsSelection=YES;中设置viewDidLoad,但这似乎没有任何区别。

我知道这可能与我的桌子在普通视图控制器中的事实有关,但我无法弄清楚我错过了使选择工作的神奇步骤。 / p>

现在我添加了一个解决方法。在cellForRowAtIndexPath中,我为单元格中的每个视图添加了UITapGestureRecognizer

for(UIView *view in cell.contentView.subviews){
    [view setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRow:)];
    [tap setNumberOfTapsRequired:1];
    [view addGestureRecognizer:tap];
    view.tag = row; // So that I can identify in the handler which row has been tapped
}

然后在处理程序中:

-(void)tapRow:(id)sender{
    UITapGestureRecognizer *gesture = (UITapGestureRecognizer*)sender;
    UIView *myView = (UIView*)gesture.view;
    int row = myView.tag;
    // Handle tap of row here
}

这实现了我的需要,但我仍然想弄清楚我对行选择做错了什么!

5 个答案:

答案 0 :(得分:1)

确保桌面视图顶部没有其他视图(例如,可能会窃取触摸事件的透明视图)。还要确保为tableview及其所有父视图启用了userInteraction。

答案 1 :(得分:1)

只是因为任何人仍然有这个问题。我刚刚意识到-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath方法不适用于设置了点按手势识别器的任何视图或子视图。因此,请从其父视图的视图中删除点按手势识别器。如果您仍想处理触摸事件,请使用“touchesBegan”功能。 ` - (void)touchesBegan:(NSSet *)触及withEvent:(UIEvent *)事件  {  [super touchesBegan:touches withEvent:event];

UITouch * touch = [触及anyObject];

}`

答案 2 :(得分:0)

我们输入错误的委托调用didDeselectRowAtIndexPath而不是didSeselectRowAtIndexPath。是你的情况吗?

我看到您可以在tableview中更新您的内容,以便连接正常。我想到了函数名称的错误。

只是为了测试:用此替换你的didSelectRowAtIndexPath函数(复制,粘贴)。

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Selected %d",indexPath.row);
}

答案 3 :(得分:0)

昨天,当我意识到我没有链接表格视图的委托和dataSource时,我的当前项目出现了两分钟完全相同的问题。你以编程方式创建它,所以它应该工作。对我来说是一个委托问题,你可以检查你的属性检查器,以确保一切正常。

答案 4 :(得分:-2)

在cellForRowAtIndexPath方法中添加此行

cell.userInteractionEnabled = NO;