![](/img/trans.png)
[英]Get indexPath of cell when it's being shown from collectionView
[英]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.