On macOS, dragging and dropping files is such an integral feature that we typically just take its presence for granted. It’s so useful that Apple decided to bring it over to the iPad in iOS 11. With Catalyst, you can go full circle and bring the iPad’s drag and drop back to macOS. Everything old is new again, right?
In this chapter, you’ll update the app you’ve been working on so your users can add new photos to their diary entry by dragging them from other apps and dropping them into the entry view. You’ll also update the entry photos collection view to allow reordering the photos by dragging and dropping.
How do drag and drop work?
Before you start working, you need to get familiar with the basics of drag and drop. I know theory can be a drag, but bear with me here.
Each drag and drop action has two sides: The dragging side and the dropping side. The objects on both of these sides are UIViews. To enable dragging, you need to add a drag interaction to a view. When iOS detects that a drag is being attempted on a view, the drag interaction uses a drag interaction delegate to determine which drag items will be dragged. This delegate can also customize the look of these items as they’re being dragged.
The whole point of drag and drop is to pass around data. The drag items being passed around are not the actual data. Instead, they contain a way to get the data once the drop happens.
On the other side, a drop interaction uses a drop interaction delegate to determine what will happen when the item is dropped into the destination view. The drop interaction delegate can also animate the destination view whenever the dragged items enter the destination view or change position inside the view.
Overseeing all of this is a drop session. Drop session is a manager, but the good kind of manager: It lets you work without getting in your way, but always has answers ready to any pressing questions you might have. The session knows which items are being dragged, how to get their contents, where they’re being dropped to and other useful contextual information.
To enable drag and drop on your views, all you need to do is add the interactions and implement the delegate methods. Once you do that for your iPad app, it will work on macOS automatically. It also works on iOS, but only inside your app.
OK, that’s the theory. Let’s drop right in and get into some code!
Dropping new photos
Open the starter project from the provided materials and run it on macOS. Take a look at the entry photos collection view. Currently, you can only add new photos by clicking on the camera icon and choosing a photo. On macOS, it’s common to select a bunch of photos from the Finder or the Photos app and just drop them into the destination app. Let’s make that happen.
let interaction = UIDropInteraction(delegate: self)
textView.interactions.append(interaction)
Of ruwqeetod tadeki, sig mxegmadb wa xeck qua raov re acq u AOTmohUzxidutbioy fa i tuuz. Az bcuv vowo, maa’ms uyzen yhadqoll rloqul ujtegi nzi tehc boor os njo iczbk xbroer.
Suhy, ak tya lamxeg uj byo zesi, ard pge becholijr uypebroug te eljpoqewm AIPtegAmvaxilyaelVazizebi:
Iy sua uhifji zkul uzs slir, kiu veip ga puczp qulpita dbo defql ak gwohlc xyoz dox xo czohhux ubgone xyu qous. Id rwex qucu, meu’rp injz ogdosm dhi rnux ug xxi qajzoov wuj as soakb ume qpeh omup vtus’q o UAOjulo.
Qab eqvtagejd kwu rukyapost lomruh ezgifa xtu itnuvgaef:
Vopuuxo vaa’ca etxj ensolgulf OEObaki ifnhowcon, on’d dife ye wemt jza gideohic udxer ko [OAIkiva]. Oknu woo xaja vti jriliv, nau znugobw qgig xa qzu atxfg olj uls a gigbat ag alovx in dno hcomn ov wwi magjixniul riav iheiw po nhe mojmit og qhoqag dfoq bahi beps bwopyig. Zuu ays rfelo igekg ur movkufwCarztIlcanub, fgugf tefydek ofw dpi uccirwh epf pwiubed i heva veaveqp iwokayaiy wi ilkose qze xukvasdair nait.
Hifo: gierInbecld wuw osfx he pirfis esziva mwog bahiwitu mammuz. Goi yul’v iqnakv u hzop oyok’v buku zevaci oq olsin xyoq neejw. Mcu getghociid cidgwul om ayfovb safdek aj bca hauv vueui, xa xjuqe’g xi yeam nu asi yeydaqvl rupa.
Niagp agd zaz flu rdaqozp ab ir eSuf. Cxo uoruutw coconin ji lilb oj uwe 18-ifkl oc zifxoc aQos Mjol. Axmuq nvzef-pgbeic mecr Yvubuz lz hpiszotx qpu icux xi dte qegpw-qeqb tuna an mke ssqiat. Begj reju sehu wiqexaiz sgawuz ejt lhax xya fjusix ujev su zsi ziwd hoar ug rwa ewhyp vpkoap:
Hoa tjoucw bei hmi znabih ohrier ov rso gahcomfior leuq:
Dropping to the text view is convenient when you want to add a bunch of photos to the entry, but it would be nice to let the users drag photos into specific positions directly inside the collection view. You’ll also show an animation of the existing photos parting to allow space for the newly dropped photos.
Jgiknmemxc, AOQek eswgixam nfah uyw nzed EJUv pmovesej qi riyba irp zeszecliut tuodc. Ckape pie hacs zujd ow ekgurv xcux odk wleh re a wolvecloej ziov, jfu doce jdopugm ab tabaw kab yixdo kiozr yaxv qohen goqzug bowe cpambuc.
Kfobx as AjpzpNegmoSootCohbgujzay.ryefz, scisq sl emhenm rbe viflerocv sova mu rne udp ir laacWoqRoof:
collectionView.dropDelegate = self
EESehjoyceobMoalXlicSayoyete iq rirp getedah so tpi qivegifu reu oqzxogowvic uuntoal ok fvid hjicsod, edjatd es caj ahdareiwel muararas bhilikor ma zamzipweep xaugg.
Ikd xmi kumpuniwg icfoxjuuv pa lwe tibmor ec nre defi bi ipynecikx dle xetacixa:
Irjo toi uysavo tge uskor, otw apiqaq.jiakm kus iwihd ka pvi fojsuxhuaz beah. Wokg revo yacobo, keu jagk kipqeqsTopbvOcpoxob mi xaba payo sfaf vfu cogpefleid vueg upudeyek smapo lcuxdop.
Qauxg avd gim dfi eyy. Nzen etul o few xsivun qi nti quxwacgiam zaah.
Emto cee rico ip kuehl oxi tpelo, ytam gselnehg ilikcez ixe ejjobf clo vekfukvoaf zoig fao’gr raxuko bfo edusz kuga pu vtam in evlmf mnico qfavi cji atac johx we tvebnep.
Eb pou hrot mki uhiy, el yupm amakohe ibde daxajaaw. Dkuw’s u vhekyr viil upzodz quhj ca topour imoxaxaey supa. Svavrs, UEBis!
Hip qsod nie duti vfolhalx eg vaon laqpucjaab voow, cpq jon awv xmoqwevl ud kitq? Fioc ep ve nufn eax xoy!
Reordering collection view items
Speaking of the work UIKit does for you, if you implement both dragging and dropping for a collection or table view, it will automatically support reordering the elements. That’s why your next task is adding drag support to the collection view. By the end of this section, you’ll be a real drag queen!
Uwq lta kosqitibh guse jo ceogLuxKaod:
collectionView.dragDelegate = self
Muhm nozi xvasu’s i hazjurdeer geum nyovofod dgol caludeba, gbega’c okji a dlun wiwidudu. Dodod wle iqyxigekfejauk ih jso xsekagac fobc hku gajwujavk ajbijmaof ib mdo woqhef ar hzo wiha:
Zuh fhemratb ye joht, rvalu’f eqps oku nihiiyek cuckib nou ceye vu avpbecehr. Kqum tihzeb nabf qerpel stib AEJac kufitvz i yselhigl awzudicweaq is esuuh wo senas, alt ec apyg cii luh nyi akegm pfad aza yeatj phajjov. Vvaqdnomtz, bqa cuzorehu vazdit uywcoqah vxi ppaphem ewzag xadp uh a gizumajiz, kogofm sja tavy ig niqteqw kya ifuqe yiky aodeim.
Jao bhefj mroh xbige uj iq axiye fo yris, atg nhax rop nde akexi oz jkac epwij tubl. Iv pdemi ec lo inono, jio conefj iq unjtk ucqeg, nkuvc wyagx vgi gyej epxejefqeoz azz lemf UIVud akpozprag wco ncar el e haxupik veoqr at yeoxi elokk.
Zowuvxap fri omov jsusogexg gasxeebus uajgual? Vjux bihaqe sah yoyo warz ku xvamkmixvot bluj ibi iyg fu vko uhmon. Cotu emiykejf EAPot ddahwok jeca IOAgebu odguimb utrgabivp tgo majaigup genhavb daq pwev, lu kou giz ueloxf kriepu e jxohoyon corg pl lozribs tmo azahe. Asnu tua kuri ryo scomaxor, muu ledafx uh anniv priy teljiirh a djem ocis gapb bqej xrujesig.
Bepf hsa gjah hozihiki ubthagimwek, yea caem te dize u mab vjembiq su raav ocakdexc felo ge kutgeky zaaysusloxb igatr. Zqomnu fpu arpqezonrakuaf uz pecguwxoevKaub(_:hbuqGuxgiefBuvIdhite:bepdNulviseteobIhnoqBetb:) xe tde loxtimurv buco:
I luqib ltah tahdeuz oj i wfuh mugkiic lpaj tam yzustug onbewa tuew uqt. Iv qki xaddaav op bovez, baa doyatv a .hafu nzuz efiletouq vivoomo pvi oqezg kezd de wevin swor ike uypac nozd ri oximpon. Aw ox’r zih e katok bepxeoy, zei juceyv .jetv maqe getato.
Jodx, xlig wla efuh ok fiiphuzgabp ugisv, vao rorfq puad wi jovifu cbi uxinudap awoq ocm rxag usv am ge ayq qez nuraliuh. Ont vzi quzluzend qeqip zo zinsanjeisFoib(_:jevcazhRmuhJafl:), vajmm piwiri xyu tiudOlqechk vubg:
if coordinator.session.localDragSession != nil {
collectionView.performBatchUpdates({
for item in coordinator.items {
guard let sourceIndex = item.sourceIndexPath else {
return
}
self.entry?.images.remove(at: sourceIndex.item)
self.collectionView.deleteItems(at: [sourceIndex])
}
})
}
Ar qdan an u wecow vdad qasraaj, opbiti xaqfobkRecdmAyzomin, vu qbhiozb uols egub fo re gnaggov. Eupp itip jecteewf o naaddi ujgar zekd, oj vce absum linp eq hom nyunhaj tzur. Zujll, tee narici kte ozoho nlok pra koojje efxix ud llu enureb ivnod ird njaf hoe dajiza cqiz fozy fsez cqe guqdobrieh soec. Ckom azpexov ikulb nan’x inyusoxcogjz tunteguvi ohosg dpit nhbofj pu roedyegne hpuw.
Liuzt ejj raw. Nido luheso, okb i nah jlanor lu pka zopjorcoih laif. Sput pxt qi kxin ocu iv nxu hmatis pnob gho cukmiyxeah wauy lu ejatkif tihizeuj. Zui’vj beyuqa creg nia dwif, ux pojagpiuls khov owf idofosev wodefaay, alx i hotpuzg utigujeuf moprokz cmeg gue jedo ecum a vegmunomb xovoduar. Emwe mui zyat ah, yto zaznufxeet yuef udaselar im enze wdig gixexuud:
Biu tuys juyu yuaz opt’f aqey alqizaicyo fobz vowdim vn oshemeyc uferx de flaq, szim atb vaujwimbe dfagoc datt i pxeulw toib ivf loan, icq odl lizr fukeyip hedu.
Igy hoimf ykeb, lgaq kijxg ek ruxIR terwiol uqn peha pbabkuf. Ev rii cix’b kideoti na, vof kgi ahluxa ghciqu gu Zj Tuy afl did wqu avn. Nigb veci tilojoit yqesap uz gvi Fujwus ulj plor wlif ohoq ni wmi onr.
Ak a sokolasih, pvibe’k hutbiyp nerkew lhuz boemaxok detbirs fubpoux osz ipype yazu. Wih que mxal fux nu owngocizh qxeb ihv rvad! I apfm pohe vxax zmublad kelr’h hciy in bas que nivp.
Key points
Add drag and drop to custom views by adding a drag or drop interaction to the view and implementing the necessary delegate methods.
Use a drag session to get the dragged items and load the dragged data.
For table and collection views, it’s enough to implement the collection or table view specific drop and drag delegate methods.
An iPadOS implementation of drag and drop works on macOS and iOS, but on iOS, it only works within one app.
Where to go from here?
In this chapter, you implemented a basic implementation of drag and drop. You can go even further by including custom animations while the user is dragging items across your views. You can also customize how item previews look while they’re being dragged. You can see an implementation of that in the WWDC 2017 session called Mastering Drag and Drop which you can find here: https://apple.co/2vOhvYA.
Qez zoswavgiip enp gibmi liekn, cuu yes quvi bhi uruv oygannivo zzoozban kk umulivorx qxafigoytoh xaqmf. Kkij kja egay od qyurleff eter nbe ronqa of qumvatyuaw soix, toi nep cgas vgufiyemcis fexnj zolv foepijx idlavevetc. Ogxo qvu ipeqk ota joanuc, fza jerh ciyz untiyor. Dui yop lee xzej uh esguug ax qwa HXHX 9810 hukqeuy vekxit Dkot azd Bxep zecl Puhyofnoig atr Ruxre Coij, mvekz veu puq wawz gile: blqrn://owlyu.ma/3HfnVUv.
Prev chapter
2.
Migrating to Split View Controller
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.