如何识别触摸的图像

时间:2016-12-08 18:02:54

标签: ios swift swift3 uigesturerecognizer

我正在开发一个应用程序,用户可以在画布上拖放项目,当他释放图像时,它会在画布上绘制。

这是我的DragImage类,用于处理触摸:

class DragImages: UIImageView {

    var originalPos : CGPoint!
    var dropTarget: UIView?

    override init (frame : CGRect){
        super.init(frame: frame)
    }

    required init?(coder aDecoder : NSCoder){
        super.init(coder : aDecoder)
    }

    override func touchesBegan(_ touches : Set<UITouch>,with event: UIEvent?){
        originalPos = self.center
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first{
            let position = touch.location(in: self.superview)
            self.center = CGPoint(x : position.x, y : position.y)
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

        if let touch = touches.first, let target = dropTarget{
            let position = touch.location(in: self.superview)
            if target.frame.contains(position){

               NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "onTargetDropped"), object: nil))
            }else {
                self.center = originalPos
            }
        }

        print(self.center.x, self.center.y)
        self.center = originalPos
    }

    func getEndPosX() -> CGFloat{
        return self.center.x
    }

    func getEndPosY() -> CGFloat {
        return self.center.y
    }

}

在我的ViewController类中,我添加了这段代码来处理触摸等:

  ornament1.dropTarget = xmasTree
    ornament2.dropTarget = xmasTree
    ornament3.dropTarget = xmasTree
    ornament4.dropTarget = xmasTree

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.itemDroppedOnTree(_:)), name: NSNotification.Name(rawValue: "onTargetDropped"), object: nil)

}


func itemDroppedOnTree(_ notif : AnyObject){



}

当我在画布上拖动图像时,我设法得到了X和Y的位置,但我无法找到一种方法来识别4个图像中的哪一个被删除,以便我绘制特定的图像!

1 个答案:

答案 0 :(得分:4)

您可以将发件人添加到您的通知中(以及位置):

NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "onTargetDropped"), object: self, userInfo: ["position":position]))

稍后在itemDroppedOnTree

中获取
func itemDroppedOnTree(_ notif : NSNotification){
    let position = notif.userInfo["position"]
    let sender = notif.object as! DragImage
    if sender === dragImage1 {
         //... 
    } else if sender === dragImage2 {
         //...
    }
 }

我建议您反对,并请求使用delegate来通知ViewController。 (基于意见:一般情况下,仅对多人广播使用通知。)

委托函数应将sender作为第一个参数。根据{{​​1}}。

通过这种方式,您可以知道哪个图片正在发送新位置,并可以将其与您的媒体资源进行比较,如上例所示:

func tableView: tableView:UITableView, cellForRowAt indexPath:IndexPath)

您的代码加上工作委托以粘贴到Playground:

 if dragImage === dragImage1 {...

结果:

相关问题