ios - UITableView 拖放到表外 = 崩溃

标签 ios swift uitableview drag-and-drop animatewithduration

好的

我的拖放功能几乎可以完美运行。我长按一个单元格,它可以让我顺利地将按下的单元格移动到其他两个单元格之间的新位置。表格会调整,更改会保存到核心数据。太棒了!

坏事

我的问题是,如果我将单元格拖到表格底部单元格下方,即使我不松开(松开)单元格...应用程序也会崩溃。如果我缓慢地拖动,当单元格穿过最后一个单元格的 y 中心时,它真的会崩溃……所以我认为这是一个与快照获取位置相关的问题。不太重要但可能相关的是,如果我长按最后一个包含值的单元格下方,它也会崩溃。

拖放操作运行一个 switch 语句,该语句根据状态运行三组代码之一:

  • 媒体开始时的一个例子
  • 单元格被拖动的一种情况
  • 用户松开手机的一种情况

我的代码改编自本教程:

Drag & Drop Tutorial

我的代码:

 func longPressGestureRecognized(gestureRecognizer: UIGestureRecognizer) {

    let longPress = gestureRecognizer as! UILongPressGestureRecognizer
    let state = longPress.state

    var locationInView = longPress.locationInView(tableView)
    var indexPath = tableView.indexPathForRowAtPoint(locationInView)

    struct My {
        static var cellSnapshot : UIView? = nil
    }
    struct Path {
        static var initialIndexPath : NSIndexPath? = nil
    }

    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! CustomTableViewCell;

    var dragCellName = currentCell.nameLabel!.text
    var dragCellDesc = currentCell.descLabel.text


    //Steps to take a cell snapshot. Function to be called in switch statement
    func snapshotOfCell(inputView: UIView) -> UIView {
        UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, false, 0.0)
        inputView.layer.renderInContext(UIGraphicsGetCurrentContext())
        let image = UIGraphicsGetImageFromCurrentImageContext() as UIImage
        UIGraphicsEndImageContext()
        let cellSnapshot : UIView = UIImageView(image: image)
        cellSnapshot.layer.masksToBounds = false
        cellSnapshot.layer.cornerRadius = 0.0
        cellSnapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0)
        cellSnapshot.layer.shadowRadius = 5.0
        cellSnapshot.layer.shadowOpacity = 0.4
        return cellSnapshot
    }


    switch state {
        case UIGestureRecognizerState.Began:
            //Calls above function to take snapshot of held cell, animate pop out
            //Run when a long-press gesture begins on a cell
            if indexPath != nil && indexPath != nil {
                Path.initialIndexPath = indexPath
                let cell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
                My.cellSnapshot  = snapshotOfCell(cell)
                var center = cell.center

                My.cellSnapshot!.center = center
                My.cellSnapshot!.alpha = 0.0

                tableView.addSubview(My.cellSnapshot!)

                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    center.y = locationInView.y

                    My.cellSnapshot!.center = center
                    My.cellSnapshot!.transform = CGAffineTransformMakeScale(1.05, 1.05)
                    My.cellSnapshot!.alpha = 0.98

                    cell.alpha = 0.0

                    }, completion: { (finished) -> Void in

                        if finished {
                            cell.hidden = true
                        }
                })
            }
        case UIGestureRecognizerState.Changed:

            if My.cellSnapshot != nil && indexPath != nil {
                //Runs when the user "lets go" of the cell
                //Sets CG Y-Coordinate of snapshot cell to center of current location in table (snaps into place)
                var center = My.cellSnapshot!.center
                center.y = locationInView.y
                My.cellSnapshot!.center = center

                var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
                var context: NSManagedObjectContext = appDel.managedObjectContext!
                var fetchRequest = NSFetchRequest(entityName: currentListEntity)
                let sortDescriptor = NSSortDescriptor(key: "displayOrder", ascending: true )
                fetchRequest.sortDescriptors = [ sortDescriptor ]


                //If the indexPath is not 0 AND is not the same as it began (didn't move)...
                //Update array and table row order
                if ((indexPath != nil) && (indexPath != Path.initialIndexPath)) {

                    swap(&taskList_Cntxt[indexPath!.row], &taskList_Cntxt[Path.initialIndexPath!.row])
                    tableView.moveRowAtIndexPath(Path.initialIndexPath!, toIndexPath: indexPath!)

                    toolBox.updateDisplayOrder()
                    context.save(nil)

                    Path.initialIndexPath = indexPath
                }
            }
        default:
            if My.cellSnapshot != nil && indexPath != nil {
                //Runs continuously while a long press is recognized (I think)
                //Animates cell movement
                //Completion block: 
                //Removes snapshot of cell, cleans everything up
                let cell = tableView.cellForRowAtIndexPath(Path.initialIndexPath!) as UITableViewCell!

                cell.hidden = false
                cell.alpha = 0.0
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    My.cellSnapshot!.center = cell.center
                    My.cellSnapshot!.transform = CGAffineTransformIdentity
                    My.cellSnapshot!.alpha = 0.0
                    cell.alpha = 1.0
                    }, completion: { (finished) -> Void in
                        if finished {
                            Path.initialIndexPath = nil
                            My.cellSnapshot!.removeFromSuperview()
                            My.cellSnapshot = nil
                        }
                })//End of competion block & end of animation

            }//End of 'if nil'

    }//End of switch

}//End of longPressGestureRecognized

潜在罪魁祸首

我的猜测是这个问题与单元格一旦低于最后一个单元格就无法获取坐标有关。它并不是真正 float 的,它不断地设置它相对于其他单元格的位置。我认为解决方案将是一个 if 语句,当没有单元格可供引用时,它会做一些神奇的事情。但是什么!?!出于某种原因,向每个案例添加 nil 检查不起作用。

明确陈述的问题

如何避免崩溃并处理我拖动的单元格被拖到最后一个单元格下方的事件?

崩溃截图:

Out of Range

最佳答案

丑陋的

看来您只需要进行先发制人的检查,以确保您的 indexPath 不是 nil:

var indexPath = tableView.indexPathForRowAtPoint(locationInView)
if (indexPath != nil) {
    //Move your code to this block
}

希望对您有所帮助!

关于ios - UITableView 拖放到表外 = 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32256784/

相关文章:

ios - 如何在 Swift 中创建一个空数组?

ios - Swift 链接错误 : type metadata accessor for Module. 类

objective-c - 如何根据对象的属性对数组进行排序?

android - Cardboard SDK Unity - 原生和共享属性的方法?

ios - ?尝试将数据源加载到 UIPickerView 时返回

swift - 在 ConstantsToExport 中导出 swift 枚举

ios - 从另一个 View 重新加载 TableView

ios - 通过委托(delegate)附加的数据未显示在表上

ios - DataSource Pattern 与 UITableView 一起使用是依赖注入(inject)的示例吗?

objective-c - 在 UITableView 中搜索 - NSInvalidArgumentException 错误