繁体   English   中英

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

[英]get indexpath from collectionView, sometime get the wrong indexPath

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

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

但是在UICollectionView中效果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
}

您正在编写此行:

delBtn.addTarget(self, action: #selector(FavViewController.DelFavAction(_:)), forControlEvents: .TouchUpInside)

在下面写另一行:

delBtn.tag = indexPath.item;

并获取项目:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM