使用平移手势从collectionView拖动新创建的子视图

时间:2016-02-17 00:04:07

标签: ios swift uicollectionview uigesturerecognizer pan

我有一个ViewController,下面有一个基本的集合视图。我现在能够单击集合视图中的单元格并添加所选图像的子视图。 我坚持允许用户按下单元格并将新的子视图拖动到主视图上而无需用户抬起手指并重新选择从而激活平移手势。

如何以编程方式为新创建的子视图启动平移手势,因此用户似乎正在从collectionView中拖出副本?

func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
    stickerImage = imageArray[indexPath.item]!

    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
    dispatch_async(dispatch_get_global_queue(priority, 0)) {
        dispatch_async(dispatch_get_main_queue()) {
            // update UI on the main thread
            var newImageView = UIImageView(image: self.stickerImage)

            newImageView.userInteractionEnabled = true
            newImageView.multipleTouchEnabled = true
            newImageView.exclusiveTouch = true
            newImageView.contentMode = .ScaleAspectFit

            let panGesture = UIPanGestureRecognizer(target: self, action:Selector("handlePan:"))
            panGesture.delegate = self
            newImageView.addGestureRecognizer(panGesture)


            newImageView.frame = self.view.bounds
            newImageView.frame.size.width = 150
            newImageView.frame.size.height = 150

            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell

            newImageView.center.y = self.view.frame.height - collectionView.frame.height / 2
            newImageView.center.x = cell.center.x

            self.view.addSubview(newImageView)
            self.view.bringSubviewToFront(newImageView)
        }
    }

}

func handlePan(recognizer:UIPanGestureRecognizer) {

    self.view.bringSubviewToFront(recognizer.view!)
    let translation = recognizer.translationInView(recognizer.view)
    if let view = recognizer.view {
        view.transform = CGAffineTransformTranslate(view.transform, translation.x, translation.y)
    }
    recognizer.setTranslation(CGPointZero, inView: recognizer.view)
}

1 个答案:

答案 0 :(得分:0)

您是否已尝试将触摸方法重写为touchbegin和touchend。覆盖这些方法,您不必关心平移手势,只需要检查识别哪个触摸的视图。