2014-01-19 22 views
1

我有一个collectionview [not custom 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]; 

    } 

什么可以是问题,谢谢!

+0

http://stackoverflow.com/questions/13757762/getting-button-action-uicollectionview - 细胞 也许这会帮助你 – NeoJiang

回答

1

看起来不像您所添加的按钮,将电池或返回的细胞,试试这个:

[cell addSubview:btn]; 
return cell; 

你有没有意识到UICollectionView有选择的委托方法? collectionView:didSelectItemAtIndexPath:

+0

是的。但当我添加collectionView:didSelectItemAtIndexPath和我点击按钮应用程序崩溃的问题?另一个细节是收集视图是一个子视图。 – santa

1

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

然后检查您的按钮的选择器方法是否首先被调用。你可以在其中添加一个NSLog语句来测试被调用的方法。此外,您应该使用DidSelectItem委托方法来检测触摸。你提到当你试图实现didSelectItem委托方法时,你的代码崩溃了,这不是避免解决问题并在其他地方实现你的选择代码的借口。修复你的崩溃并正确地执行它的家伙。让我们知道当您尝试实施didSelectItem委托方法时崩溃的实际情况,以便我们可以进一步提供帮助。

更新1 重新创建您的笔尖,需要在以下post的答案。它指的是你的单元格是hi视图而不是UICOllectionView,这很可能是你的内容视图没有接收到触摸事件的原因

+1

OP对我来说很明显,对Obj-C知之甚少,应该刷新。所提供的代码中存在大量错误。 拿这个人建议和*“修复你的崩溃,并适当地执行它dude”* –

+0

CollectionCell * cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath]; NSArray * sectionArr = [self.ClassesArr objectAtIndex:indexPath.section]; NSDictionary * data = [sectionArr objectAtIndex:indexPath.row]; [cell.img addTarget:self action:@selector(subCateBtnAction :) forControlEvents:UIControlEventTouchUpInside]; return cell; } 在collectionView:cellForItemAtIndexPath,我这样做,但我无法看到我的collectionview中的任何信息。 – santa

+0

[self.collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@“CollectionCell”]; 也在viewdidload,我注册了自定义单元格,但没有结果:S – santa