我最近研究了集合视图。我需要让一些单元格在自己的索引路径中修复,这意味着它们不应该被其他人交换而不能被拖动。我现在可以使用* - (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath )indexPath 来阻止它们拖动。我不能阻止它们被其他细胞交换。
任何人遇到同样的问题?
由于
答案 0 :(得分:4)
func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath {
if proposedIndexPath.row == data.count {
return IndexPath(row: proposedIndexPath.row - 1, section: proposedIndexPath.section)
} else {
return proposedIndexPath
}
}
答案 1 :(得分:1)
我发现,当我使用iOS 11+拖放功能时,targetIndexPathForMoveFromItemAt
不会被调用。实施此方法可禁止将该项目放置在我不希望的位置:
func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
// disallow dragging across sections
guard let sourcePath = session.items.first?.localObject as? IndexPath,
let destPath = destinationIndexPath,
sourcePath.section == destPath.section
else {
return UICollectionViewDropProposal(operation: .forbidden)
}
return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}
请注意,在拖动开始时,我将源索引路径存储在localObject
中,因为否则找不到其他方法来获取此信息。
答案 2 :(得分:0)
尝试使用collectionView(_ collectionView: UICollectionView,
targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath,
toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath
请参阅Apple的文档:https://developer.apple.com/documentation/uikit/uicollectionviewdelegate/1618052-collectionview
在项目的交互式移动期间,集合视图调用 此方法可以查看是否要提供不同的索引路径 拟议的路径。您可以使用此方法来阻止用户 将项目放在无效的位置。例如,你可能 防止用户丢弃特定部分中的项目。
因此,例如,如果您想要阻止使用最后一个单元重新排序单元格:
func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath {
if proposedIndexPath.row == data.count {
return IndexPath(row: proposedIndexPath.row - 1, section: proposedIndexPath.section)
} else {
return proposedIndexPath
}
}
答案 3 :(得分:0)
在此示例中,您无法在CollectionView中移动数组的第一个和最后一个组件 您可以使用porposedIndexPath,这是针对UiCollectionView委托
快捷键3
func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath {
if proposedIndexPath.row == 0 || proposedIndexPath.row == yourArray.count - 1{
return IndexPath(row: 1, section: 0)
}
return proposedIndexPath
}