Ken*_*hen 3 ios uicollectionview
我最近研究了集合视图。我需要让一些单元格固定在它们自己的索引路径中,这意味着它们不应该被其他单元交换并且不能被拖动。我现在可以使用*-(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath )indexPath来防止它们拖动。我不能阻止它们被其他单元交换。
有人遇到同样的问题吗?
谢谢
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
}
}
Run Code Online (Sandbox Code Playgroud)
我发现当我使用 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)
}
Run Code Online (Sandbox Code Playgroud)
请注意,我在拖动开始时存储了源索引路径localObject,因为否则我找不到获取此信息的方法。
尝试使用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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1599 次 |
| 最近记录: |