调用touchesEnded时删除视图

时间:2019-09-29 18:30:32

标签: swift

当用户触摸并按住手指在屏幕上时,我使用touchesBegan在屏幕上添加视图

请参见下面的示例

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let location = touch.location(in: view)
            let dot = CustomTouch(frame: CGRect(x: location.x, y: location.y, width: 80, height: 80))
            dot.backgroundColor = randomColors[0]
            self.view.addSubview(dot)
        }
    }

我想检测用户何时从屏幕上抬起手指,然后删除在该位置添加的视图。我想要一些有关如何实现这一目标的想法

2 个答案:

答案 0 :(得分:0)

为添加的视图添加属性,而不是动态创建,然后如果在touchesEnded上存在,则将其删除:

var dot: CustomTouch?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let location = touch.location(in: view)
        dot = CustomTouch(frame: CGRect(x: location.x, y: location.y, width: 80, height: 80))
        dot.backgroundColor = randomColors[0]
        self.view.addSubview(dot)
    }
}

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

答案 1 :(得分:0)

这为我完成了工作: 1)创建一个字典来存储每个为特定触摸创建的“ CustomTouch” 2)当touchesEnded结束时,我将删除该键(UITouch)的对象