问题描述
我有一个tableView和collectionView并获取indexPath我在tableViewCell和collectionViewCell上使用以下方法(我不想使用indexPathForSelectedRow / Item方法)。有什么方法可以使我通用吗?
请给我一个想法
// For Tableview
func getIndexPath() -> IndexPath? {
guard let superView = self.superview as? UITableView else {
return nil
}
let indexPath = superView.indexPath(for: self)
return indexPath
}
// For CollectionView
func getIndexPath() -> IndexPath? {
guard let superView = self.superview as? UICollectionView else {
return nil
}
let indexPath = superView.indexPath(for: self)
return indexPath
}
解决方法
您可以使用两种协议来做到这一点,一种既UITableView
和UICollectionView
都符合,又一个UITableViewCell
和UICollectionViewCell
都符合。
protocol IndexPathQueryable: UIView {
associatedtype CellType
func indexPath(for cell: CellType) -> IndexPath?
}
protocol IndexPathGettable: UIView {
associatedtype ParentViewType: IndexPathQueryable
}
extension UITableView : IndexPathQueryable { }
extension UICollectionView : IndexPathQueryable { }
extension UICollectionViewCell : IndexPathGettable {
typealias ParentViewType = UICollectionView
}
extension UITableViewCell : IndexPathGettable {
typealias ParentViewType = UITableView
}
extension IndexPathGettable where ParentViewType.CellType == Self {
func getIndexPath() -> IndexPath? {
guard let superView = self.superview as? ParentViewType else {
return nil
}
let indexPath = superView.indexPath(for: self)
return indexPath
}
}
实际上,您不需要在表视图单元格上需要getIndexPath
方法。单元格不应该知道其索引路径。我建议您重新考虑设计。