在上一篇文章中我們已經實現了用UIDragInteraction 和UIView的新屬性pasteConfiguration實現了簡單的拖動粘貼操作。
以下我們將繼續深入一點研究Drag and Drop 并實現拖動換位置和拖動進行Copy功能,
如圖:
與之前簡單使用pasteConfiguration不同,此次我們要自己來同時實現幾個UIDragInteractionDelegate和UIDropInteractionDelegate的關鍵方法。
Drag to move
Step 0 TimeLine
首選了解一下Drag and Drop 的生命周期,如上圖。
當你長按住一個視圖的時候,視圖升起時候Drag就開始了,然后隨著手指的移動這一段都是Drag, 一旦松開手指,就由Drop來接管了,繼續進行一些動畫或者數據傳輸等操作,這應該比較好理解,所以先處理Drag啦。
Step1 給View添加Drag和Drop
這部分關于UIDragInteraction&UIDropInteraction的上一篇文章Drag and Drop for iOS11已經介紹過。
我們創建一個ImageView來支持drag, 同時也要讓當前的父view支持drop:
//Config for drag image
let dragImage = UIImage.init(named: "madao")
dragImageView = UIImageView.init(frame: CGRect.init(x: 50, y: 80, width: kImageSizeWidth, height: kImageSizeHeight))
dragImageView.isUserInteractionEnabled = true
dragImageView.backgroundColor = UIColor.clear
dragImageView.image = dragImage
dragImageView.clipsToBounds = true
dragImageView.contentMode = .scaleAspectFill
//Add an UIDragInteraction to support drag
dragImageView.addInteraction(UIDragInteraction.init(delegate: self))
view.addSubview(dragImageView)
//Add UIDropInteraction to support drop
view.addInteraction(UIDropInteraction.init(delegate: self))
Step2 實現DragInteractionDelegate
最重要的,就像UITableView中的dataSource一樣,我們提供可以拖動的數據源:
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
let dragImage = dragImageView.image
//使用該圖片作為拖動的數據源,由NSItemProvider負責包裝
let itemProvider = NSItemProvider.init(object: dragImage!)
let dragItem = UIDragItem.init(itemProvider: itemProvider)
return [dragItem]
}
Step3 實現DropInteractionDelegate
首先類似itemsForBeginning方法在UIDragInteractionDelegate中的重要地位一樣,要想一個view能夠響應一個Drop,我們需要實現:
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal
該代理方法當你手指在view上拖動的時候會響應,意義在于告訴view,drop是什么類型的。主要是以下這幾種:
- cancel: 不響應Drop動作,應該可以理解成無視。
- copy:拷貝,右上角會顯示+號,當然拷貝的操作是要我們自己配合delegate來完成
- move:雖然看上去和cancel一模一樣,但是程序中還是會判定視圖可以響應這個drop事件,同樣,我們也要在delegate中完成相應代碼來使他“看上去”像一個move的動作
- forbidden:表示該視圖支持drop,但是當前暫時不支持響應(有任務block住了或者文件類型不支持之類的)
總之我們需要在上面那個delegate中告訴這個view該如何響應drop,如下:
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
//原程序設計通過segmentControl來選擇操作,所以這里通過判斷來返回不同的UIDropProposal,如果單純為了實現Move功能,也可以直接返回UIDropProposal.init(operation: UIDropOperation.move)
let operation = segmentControl.selectedSegmentIndex == 0 ? UIDropOperation.move : .copy
let proposal = UIDropProposal.init(operation: operation)
dropPoint = session.location(in: view)
return proposal
}
然后我們實現performDrop:
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
//我們這里可以獲取到dropSession在視圖中的位置,然后就可以將ImageView直接移動到那個點。
let dropPoint = session.location(in: interaction.view!)
self.selectedImageView.center = dropPoint
}
Take a break
以上步驟完成后,運行后應該可以看到我們已經簡單實現了一個Drag to move的功能,雖然可能相比使用手勢會稍顯麻煩,但是蘋果提供的動畫讓他顯得更炫酷。
Step4 動畫
UIDragInteractionDelegate和UIDropInteractionDelegate也提供給我們了一些很好的方法讓在Drag 和Drop的timeline中執行我們自己的動畫,
這里舉一個例子:
func dropInteraction(_ interaction: UIDropInteraction, item: UIDragItem, willAnimateDropWith animator: UIDragAnimating) {
if segmentControl.selectedSegmentIndex == 0 {
//Move,使用提供的參數animator去添加我們想要的動畫
animator.addAnimations {
self.selectedImageView.center = self.dropPoint!
}
animator.addCompletion { _ in
self.selectedImageView.center = self.dropPoint!
}
}
還是蠻方便的,以上就是Drag to move 的實現。
Drag to copy
其實和上文的Drag to move幾乎一模一樣,都是實現幾個關鍵的delegate方法(可以復習一下哪幾個delegate方法必須要實現)和錦上添花的動畫方法。
不一樣的就是需要傳輸數據。
可能有人會說 那我在performDrop的時候直接把imageView 復制到新位置不就好了么,雖然這樣可以,但是也失去了Drag and Drop這個功能使用的意義。
我覺得它的意義更在于底層看不見的數據隨著手指的流動,因為Drag and drop 不止于在自己的App內進行傳輸。
前文我們說到在Drag中需要用NSItemProvider來包裝這個image,同樣在Drop中我們也要使用NSItemProvider來解開這個數據并進行展示,直接貼代碼:
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
self.dropPoint = session.location(in: interaction.view!)
//Must implement this method
if session.localDragSession == nil {
self.dropPoint = session.location(in: interaction.view!)
for dragItem in session.items {
//從傳過來的dragItem中獲取數據的NSItemProvider
createImageFromProviderAndPoint(provider: dragItem.itemProvider, point: self.dropPoint!)
}
} else {
self.selectedImageView.center = self.dropPoint!
}
}
private func createImageFromProviderAndPoint(provider:NSItemProvider, point:CGPoint) {
//創建一個新的imageView
let newImageView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: kImageSizeWidth, height: kImageSizeHeight))
newImageView.center = point
newImageView.isUserInteractionEnabled = true
newImageView.backgroundColor = UIColor.clear
//使用NSItemProvider 直接加載UIImage
provider.loadObject(ofClass: UIImage.self, completionHandler: { (object, error) in
//成功后直接顯示
if object != nil {
DispatchQueue.main.async {
newImageView.image = (object as! UIImage)
newImageView.addInteraction(UIDragInteraction.init(delegate: self))
self.view.addSubview(newImageView)
}
}
else {
// Handle the error
}
})
}
當然前面的proposal也要返回copy,這樣在拖動時,視圖的右上角才會顯示+號。
當你完成以上代碼之后,應該就可以Drag to copy了。
在iPad分屏模式下,來回拖動相冊的照片到這個demo里面或者把demo的圖片拖到系統相冊也是可以的哦,這要歸功于強大的delegates和NSItemProvider
-----
demo地址:https://github.com/madao1237/DragAndDropResearch