将表格单元格拖动到接收的UIView中

时间:2019-06-12 21:40:31

标签: swift uitableview uiview draggable

我有一个表,我想选择两个对象(表行)进行比较。我想通过长按手势来执行此操作,它会创建单元格的UIView副本并将其添加到超级视图,然后我可以将其拖到表的外部到正在接收的UIView中,然后将显示此拖动的UIView,然后拖动的对象将从视图中删除。

@objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer){

        let touchPoint = gestureRecognizer.location(in: tableView)
        let longpress = gestureRecognizer as! UILongPressGestureRecognizer
        let state = longpress.state
        let locationInView = longpress.location(in: self.tableView)
        let locationInSuperView = longpress.location(in: self.view.superview)
        if let indexPath = tableView.indexPathForRow(at: touchPoint) {
            print("Selected Index equals \(indexPath)")

            switch state {
            case .began:
                if indexPath != nil {
                    Path.initialIndexPath = indexPath
                    let cell = self.tableView.cellForRow(at: indexPath) as! measurementTableCell
                    My.cellSnapShot = snapshopOfCell(inputView: cell)
                    var center = cell.center
                    My.cellSnapShot?.center = center
                    My.cellSnapShot?.alpha = 0.0
                    self.view.addSubview(My.cellSnapShot!)

                    UIView.animate(withDuration: 0.25, animations: {
                        My.cellSnapShot?.center = locationInView
                        My.cellSnapShot?.alpha = 0.98
                    }, completion: { (finished) -> Void in
                        if finished {
                        }
                    })
                }

            case .changed:
                print("Case changed")
                My.cellSnapShot?.center = locationInSuperView

          default:
                let cell = self.tableView.cellForRow(at: Path.initialIndexPath!) as! measurementTableCell

                 cell.alpha = 0.0

        }
    }


func snapshotOfCell(inputView: UIView) -> UIView {

    UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, false, 0.0)
    inputView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    let cellSnapshot : UIView = UIImageView(image: image)
    cellSnapshot.layer.masksToBounds = false
    cellSnapshot.layer.cornerRadius = 0.0
    cellSnapshot.layer.shadowOffset = CGSize(width: -5.0, height: 0.0)
    cellSnapshot.layer.shadowRadius = 5.0
    cellSnapshot.layer.shadowOpacity = 0.4
    return cellSnapshot
}

struct My {
    static var cellSnapShot: UIView? = nil
}

struct Path {
    static var initialIndexPath: IndexPath? = nil
}

上面是添加到我的tableView中的手势。当前,它使用snapshotOfCell函数创建UIView并将其添加到主视图。我可以拖动它,但是似乎仍然局限于tableView的范围。图像是在此范围之外绘制的,但是就像中心的位置仅限于图形范围一样。有没有其他方法可以获取整个UIView或窗口的指针位置,而不是获取表视图中的指针位置?

0 个答案:

没有答案