2012-12-20 53 views
5

有没有一种方法可以从UICollectionViewCell中的按钮获得按钮点击事件?我用一个笔尖填充集合视图,单元格有按钮,但它的动作没有被调用。我认为问题在于被调用的代表。我怎样才能解决这个问题?在UICollectionView中实现按钮点击

如何创建:

  1. 添加一个空的笔尖,创建了集合观察室
  2. 增加了h和.m文件和所作的细胞笔尖的文件的所有者为创建
  3. 写的类在课堂上的一个动作。
  4. 连接的按钮操作

有没有一种方法,我可以得到的行动? 我在做什么错?

+0

你有FileOwner功能?请尝试删除指向操作的链接并重新连接。 –

+0

编辑该问题 –

+0

关闭请求?为什么?哦好吧编辑 –

回答

10

添加按钮操作是这样的:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CellId" forIndexPath:[indexPath row]]; 

    [[cell myButton] addTarget:self action:@selector(myClickEvent:event:) forControlEvents:UIControlEventTouchUpInside]; 

    return cell; 

} 


- (IBAction)myClickEvent:(id)sender event:(id)event { 

    NSSet *touches = [event allTouches]; 

    UITouch *touch = [touches anyObject]; 

    CGPoint currentTouchPosition = [touch locationInView:_myCollectionArray]; 

    NSIndexPath *indexPath = [_myCollectionArray indexPathForItemAtPoint: currentTouchPosition]; 

} 
+1

这个代码并不是必需的,只需要使用Nib即可。 – MacMark

20

你从对象面板拖动“集合视图小区”创建笔尖细胞是很重要的。如果您使用UIView并只是在Identity Inspector中更改此单元的类,则该操作将不起作用。

+0

这是我确切的问题。很高兴我发现了这个建议。 – Hendrix

1

这里是SWIFT 3.1代码

// make a cell for each cell index path 
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    // get a reference to our storyboard cell 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! BlueCircleViewCell 

    // Use the outlet in our custom class to get a reference to the UILabel in the cell 
    cell.bgImage.image = UIImage(named: items[indexPath.row]) 
    cell.addButton.addTarget(self, action: #selector(addCircle(_:)), for: .touchUpInside) 

//  cell.backgroundColor = UIColor.cyan // make cell more visible in our example project 

    return cell 
} 

func addCircle(_ sender:UIButton){ 
    //CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView]; 
    let buttonPosition:CGPoint = sender.convert(.zero, to: self.collectionView) 
    let indexPath:IndexPath = self.collectionView.indexPathForItem(at: buttonPosition)! 
    onAddBlueCircle(indexPath: indexPath) 
}