Search code examples
swifttouchesbegantouchesmovedtouchesended

Touchesmoved - updating multiple elements on single drag


I'm trying to update multiple images upon clicking and dragging over the elements. I've implemented touchesbegan, touchesmoved, and touchesended, but I don't know how to make touchesmoved effect multiple images.

I've been scouring the web, but I haven't been able to find any guides on this. If you could point me in the right direction, or provide me with some basic advice, that would be greatly appreciated.

The following is an example image:

Edit: The following is an example image of what should be possible:

What it should look like.

I'd like to be able to effect the other letters in the same way through the same press, changing their pictures. These pictures are temporary images.

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    print("touches began:\(touches)")
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
            self.image = UIImage(named: "slot")!
        print("touches moved:\(touches)")
    }

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.image = UIImage(named: "tile")!
        print("touches ended")
    }

Solution

  • If I understood you correctly, that should be something like this:

    class ChangableView: UIView {
        private var touchedImageView: UIImageView? {
            didSet {
                if oldValue == touchedImageView { return }
                if let oldValue = oldValue {
                    oldValue.image = UIImage(named: "tile")!
                }
                if let newValue = touchedImageView {
                    newValue.image = UIImage(named: "slot")!
                }  
            }
        }
    
        override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            guard let touch = touches.first else { return }
            updateTouchedImageViewWithTouch(touch, event: event)
        }
    
        override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
            guard let touch = touches.first else { return }
            updateTouchedImageViewWithTouch(touch, event: event)
        }
    
        override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
            touchedImageView = nil
        }
    }
    
    private extension ChangableView {
        func updateTouchedImageViewWithTouch(touch: UITouch, event: UIEvent?) {
            let touchPoint = touch.locationInView(self)
            let touchedView = self.hitTest(touchPoint, withEvent: event)
            touchedImageView = touchedView as? UIImageView
        }
    }
    

    In addition your UIViewController should have as view a subclass of ChangableView and do not forget to set userInteractionEnabled property to all the UIImageViews to YES.