ios - 使用平移手势从 collectionView 中拖动新创建的 subview

标签 ios swift uicollectionview uigesturerecognizer pan

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

如何以编程方式为新创建的 subview 启动平移手势,使用户看起来像是从 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)
}

最佳答案

您是否尝试过重写触摸方法,例如 touchbegin 和 touchend。重写这些方法,您将不必关心平移手势,只需检查识别触摸的 View 。

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

相关文章:

ios - 如何过滤存储在数据库中的一组特定用户?

ios - 你怎么知道要提供哪个字符串作为 Swift 函数的选择器?

ios - UICollectionView cellForItemAt indexPath 在 iOS 10 中跳过行索引

iphone - 用数据填充实体后创建核心数据关系

ios - 如何在没有 segue 的情况下使用通知中心将数据从第一个 TableView 发送到第二个 TableView

iphone - 以编程方式添加 UITableView - 如何设置单元格的重用标识符?

ios - 如何在 Swift 中更改 UIButton 图像

swift - 单元格之间的空间 UICollectionViewLayout

ios - GridView (UICollectionView)的偏移量随着分页滚动而逐渐变化

ios - 使用 afnetworking 3.0 将应用程序视频上传到服务器