Body
Function
Use Uicollectionview to achieve a location interaction between two cells or to drag a location to delete
Problem
iOS 11 Drag Delete will crash, no problem in iOS 9, 10
Error
017-10-11 11:38:02.692004+0800 mocr[2585:1047221] * * * terminating app due to uncaught exception ' Nsinternalinconsistencyexception ', Reason: ' Attempting to invalidate a item at an invalid Indexpath: <nsindexpath:0x1 c442a680> {length = 2, Path = 0-1} globalindex:1 numitems:1 '
First throw Call stack:
(0x181f3bd38 0x181450528 0x181f3bc0c 0x1828cac24 0x18be1091c 0x18bdd2ab8 0x18b4b74ac 0x18b4b48b8 0x18b569a4c 0x18bdd9e98 0x10275d49c 0x10275d45c 0x102762050 0x181ee3f20 0x181ee1afc 0x181e022d8 0x183c93f84 0x18b3af880 0x1009a753c 0X18192656C)
Libc++abi.dylib:terminating with uncaught exception of type NSException
Code
Func handlelonggesture (gesture:uilongpressgesturerecognizer) { switch (gesture.state) {case . Began: Guard Let Selectedindexpath = Self.collectionView.indexPathForItem (at:gesture.location (In:self.collectionView)) else { break } Collectionview.begininteractivemovementforitem (at:selectedindexpath) case . Changed: collectionview.updateinteractivemovementtargetposition (Gesture.location (in:gesture.view!)) case. Ended: self.collectionView.endInteractiveMovement () //Detect if delete operation is deleted, delete data and call Reloaddata () Default: collectionview.cancelinteractivemovement () }}
Analysis
The test discovery calls Begininteractivemovementforitem and endinteractivemovement also trigger the reloaddata operation, which calls two reloaddata before and after the deletion, but Reloaddata is an asynchronous operation, so it's an error.
Solve
Func handlelonggesture (gesture:uilongpressgesturerecognizer) { switch (gesture.state) {case . Began: Guard Let Selectedindexpath = Self.collectionView.indexPathForItem (at:gesture.location (In:self.collectionView)) else { break } Collectionview.begininteractivemovementforitem (at:selectedindexpath) case . Changed: collectionview.updateinteractivemovementtargetposition (Gesture.location (in:gesture.view!)) case. Ended: self.collectionView.endInteractiveMovement () DispatchQueue.main.asyncAfter (Deadline: . Now () +. Milliseconds, execute: {[weak self] in //detects whether to delete the operation, delete the data and call Reloaddata () }) Default: collectionview.cancelinteractivemovement () }}
Plus a deferred processing.
"Swift 4.0" IOS one uicollectionview long press Drag to delete crash problem