如何解决自定义数据不适用于 itemProvider 以实现拖放集合视图功能 - Swift
我有一个集合视图,它显示在名为“claimData”的自定义数据模型(结构)中排列的数据。
claimData 声明:
struct claimData {
var image = UIImage()
var imageTitle = String()
var hasCustomDescription = Bool()
var customDescription = String()
var isAnInitial = Bool()
var isdamage = Bool()
var isUnrelated = Bool()
var isAnoption = Bool()
var isACondition = Bool()
}
我通过 sharedInstance 共享此数据的状态,因为我使用的是浮动面板。
class PageDataSource {
var theData: ReviewDataController?
static let sharedInstance = PageDataSource()
private init() {}
}
ReviewDataController 只包含一个名为“tableViewReviewData”的 claimData 数组。
我正在尝试在我的浮动面板的 collectionView 中实现拖放功能,但我似乎无法让 itemProvider 与我的自定义数据模型一起工作。
这是我目前所拥有的:
func collectionView(_ collectionView: UICollectionView,itemsForBeginning session: UIDragSession,at indexPath: IndexPath) -> [UIDragItem] {
let item = PageDataSource.sharedInstance.theData?.tableViewReviewData[indexPath.item]
let itemProvider = NSItemProvider(object: item)
let dragItem = UIDragItem(itemProvider: itemProvider)
dragItem.localObject = item
return [dragItem]
}
这是我为 itemProvider 遇到的错误: “参数类型'claimData?'不符合预期的类型“NSItemProviderWriting””
感谢您的帮助,如果您有任何问题,请告诉我!!
解决方法
我找到了另一种方法来完成相同的集合视图单元格重新排序操作,该操作适用于自定义数据并且设置起来并不困难。
@objc func handleLongPressGesture(_ gesture: UILongPressGestureRecognizer) {
guard let collectionView = myCollectionView else {
return
}
switch gesture.state {
case .began:
guard let targetIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
return
}
collectionView.beginInteractiveMovementForItem(at: targetIndexPath)
case .changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: collectionView))
case .ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
}
}
func collectionView(_ collectionView: UICollectionView,canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView,moveItemAt sourceIndexPath: IndexPath,to destinationIndexPath: IndexPath) {
if let item = PageDataSource.sharedInstance.theData?.tableViewReviewData.remove(at: sourceIndexPath.row) {
PageDataSource.sharedInstance.theData?.tableViewReviewData.insert(item,at: destinationIndexPath.row)
} else {
print("The item could NOT be moved!!!")
}
}
并在 viewDidLoad 中简单地添加一个长按手势识别器,如下所示:
let gesture = UILongPressGestureRecognizer(target: self,action: #selector((handleLongPressGesture(_:))))
myCollectionView.addGestureRecognizer(gesture)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。