gpt4 book ai didi

ios - 从collectionView中获取indexpath,有时会获取错误的indexPath

转载 作者:行者123 更新时间:2023-11-30 13:23:58 24 4
gpt4 key购买 nike

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

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
}

最佳答案

你要写这行:

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;
}

关于ios - 从collectionView中获取indexpath,有时会获取错误的indexPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37430679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com