从collectionView获取indexpath,有时会得到错误的indexPath

时间:2016-05-25 07:38:59

标签: ios swift uicollectionview uicollectionviewcell

UItableView中的

我们可以使用这些代码从indexPath获取UITableView

extension UIView{  
  func getButtonIndexPath(tableView:UITableView) -> NSIndexPath{
            let buttonOriginInTableView = self.convertPoint(CGPointZero, toView: tableView)
            return tableView.indexPathForRowAtPoint(buttonOriginInTableView)!
        }
}

但它在UICollectionView

中的效果并不好
extension UIView{
    func getIndexPath(uc:UICollectionView) -> NSIndexPath?{
        let senderP = CGPointMake(0, self.frame.height / 2)
            let point : CGPoint = self.convertPoint(senderP, toView:uc)
            let ind = uc.indexPathForItemAtPoint(point)
            print("what i click is", point, ind)
        return ind
}

我把它放在UICollectionView

中的单元格按钮中
delBtn.addTarget(self, action: #selector(FavViewController.DelFavAction(_:)), forControlEvents: .TouchUpInside)

,功能是

    func DelFavAction(sender:UIButton){
    guard let indexPath = sender.getIndexPath(self.collectionView) else {
    return
    }
    print(indexPath)
}

但大多数情况下错误indexPath.item,这是怎么回事?

与此代码有关吗?

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return rectArr[indexPath.item].size
}

1 个答案:

答案 0 :(得分:0)

你写的这行:

delBtn.tag = indexPath.item;

下面写下其他一行:

func DelFavAction(sender:UIButton){
//        sender.tag to convert uibutton;
//  for objectvie C write: UIButton *btn = (UIButton *)sender;
}

并获取项目:

rel_status==$relation1