我下面有一个具有基本集合视图的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)
}

最佳答案

您是否尝试过覆盖touch方法,例如touchbegin和touchend。覆盖这些方法,您不必关心平移手势,只需检查可识别触摸的视图即可。

关于ios - 使用平移手势从collectionView拖动新创建的 subview ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35445430/

10-10 21:33