1

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")
    }
4

1 回答 1

1

如果我理解正确,那应该是这样的:

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
    }
}

此外,您的 UIViewController 应该有一个 ChangableView 的子类作为视图,并且不要忘记将所有 UIImageViews 的 userInteractionEnabled 属性设置为 YES。

于 2016-09-04T21:07:06.293 回答