无法检测按钮操作集合视图



我有一个collectionview[而不是自定义collectionview],我想通过单击按钮来显示警报。但是按钮操作无法检测到我的代码:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [ self.collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
NSArray *sectionArr=[self.ClassesArr objectAtIndex:indexPath.section];
NSDictionary *data =  [sectionArr objectAtIndex:indexPath.row];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(54, 25, 15, 15);
[btn addTarget:self action:@selector(subCateBtnAction:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:btn];
}

// the button action
-(IBAction)subCateBtnAction:(UIButton *)btn
{
NSArray *sectionArr=[self.ClassesArr objectAtIndex:sectionindex];
NSDictionary *data =  [sectionArr objectAtIndex:btn.tag];
NSString *name = [data objectForKey:@"nombreTarifa"];
UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:@""
message:name
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[Notpermitted show];
}

怎么了,谢谢!

看起来没有将按钮添加到单元格或返回单元格,请尝试以下操作:

[cell addSubview:btn];
return cell;

但是您是否意识到UICollectionView有一个委托选择方法?collectionView:didSelectItemAtIndexPath:

哇,你永远不想在cellForItemAtIndexPath:委托方法中添加这样的按钮,EVER!创建一个自定义单元格视图并在其中添加按钮,然后在该代码中创建按钮的实例

然后检查是否首先调用了按钮的选择器方法。您可以在其中添加NSLog语句,以测试正在调用的方法。此外,您应该使用DidSelectItem代理方法来检测触摸。您提到,当您尝试实现didSelectItem委托方法时,您的代码崩溃了,这并不是避免解决问题并在其他地方实现选择代码的借口。修复你的崩溃并正确实施,伙计。当您尝试实现didSelectItem委托方法时,请告诉我们崩溃的实际原因,以便我们能够进一步帮助您。

更新1重新创建你的笔尖,需要在下面的帖子中找到答案。它指的是你的单元格是一个hi视图,而不是UICOollectionView,这很可能是你的内容视图没有接收到触摸事件的原因

最新更新