有没有办法可以从 a 中的按钮获取按钮单击事件UICollectionViewCell
?我用笔尖填充集合视图,单元格有按钮,但它的动作没有被调用。我认为问题在于被调用的代表。我怎样才能解决这个问题?
我是如何创建的:
- 添加了一个空笔尖,创建了一个集合视图单元格
- 添加了一个 .h 和 .m 文件,并将单元笔尖的文件所有者作为创建的类
- 在课堂上写了一个动作。
- 将按钮连接到动作
有没有办法让我采取行动?我究竟做错了什么?
有没有办法可以从 a 中的按钮获取按钮单击事件UICollectionViewCell
?我用笔尖填充集合视图,单元格有按钮,但它的动作没有被调用。我认为问题在于被调用的代表。我怎样才能解决这个问题?
我是如何创建的:
有没有办法让我采取行动?我究竟做错了什么?
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.
像这样添加按钮操作:
- (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];
}
这是 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)
}