5

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

我是如何创建的:

  1. 添加了一个空笔尖,创建了一个集合视图单元格
  2. 添加了一个 .h 和 .m 文件,并将单元笔尖的文件所有者作为创建的类
  3. 在课堂上写了一个动作。
  4. 将按钮连接到动作

有没有办法让我采取行动?我究竟做错了什么?

4

3 回答 3

20

It is important that you create the cell in the Nib by dragging a "Collection View Cell" from the Objects panel. If you use an UIView and just change the class for this cell in the Identity Inspector then the action will not work.

于 2013-05-13T12:01:17.417 回答
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];

}
于 2012-12-20T07:40:19.320 回答
4

这是 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)
}
于 2017-07-31T06:30:33.137 回答