我的集合视图标题中有一个名为"Select“的按钮。如何在按钮的单击操作中获取节id,以便迭代此节中的单元格元素并将其标记为选中?
发布于 2019-03-10 16:11:50
您可以在UICollectionView
的扩展中添加func indexPathForSupplementaryElement(ofKind kind: String, at point: CGPoint) -> IndexPath?
方法
extension UICollectionView {
func indexPathForSupplementaryElement(ofKind kind: String, at point: CGPoint) -> IndexPath? {
let targetRect = CGRect(origin: point, size: CGSize(width: 0.1, height: 0.1))
guard let attributes = collectionViewLayout.layoutAttributesForElements(in: targetRect) else { return nil }
return attributes.filter { $0.representedElementCategory == .supplementaryView && $0.representedElementKind == kind }.first?.indexPath
}
}
并在您的UIViewController
中使用它,例如
@IBAction func didSelectHeader(sender: UIView, forEvent event: UIEvent) {
guard let point = event.allTouches?.first?.location(in: collectionView) ?? sender.superview?.convert(sender.center, to: collectionView) else { return }
guard let indexPath = collectionView.indexPathForSupplementaryElement(ofKind: UICollectionView.elementKindSectionHeader, at: point) else { return }
// do something with the indexPath
}
在我们的例子中,indexPath.item
每次都是0,但是indexPath.section是不同的,这取决于报头相对于collectionView
部分的位置
https://stackoverflow.com/questions/39520273
复制