Touchesmoved - 在单次拖动时更新多个元素

时间:2016-09-04 08:33:56

标签: swift touchesbegan touchesmoved touchesended

我试图在单击并拖动元素时更新多个图像。我已经实现了touchesbegan,touchesmoved和touchesended,但我不知道如何使touchesmoved效果多个图像。

我一直在网上搜索,但我还没有找到任何指南。如果你能指出我正确的方向,或者给我一些基本的建议,那将非常感激。

以下是示例图像:

编辑:以下是应该尽可能的示例图像:

What it should look like.

我希望能够通过相同的印刷机以相同的方式影响其他字母,更换图片。这些图片是临时图片。

console.logged

1 个答案:

答案 0 :(得分: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。