swift - 调用touchesEnded时移除 View

标签 swift

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

参见下面的示例

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

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

最佳答案

为添加的 View 添加一个属性,而不是动态创建,然后删除(如果在 TouchsEnded 上存在的话):

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

关于swift - 调用touchesEnded时移除 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58158071/

相关文章:

ios - 如何从 Swift 的核心数据中删除特定的实体数据?

ios - 为什么scrollView在swift中不会是不定式?

ios - 无法删除手势

iOS FBSDKLogin 按钮文本淡入

ios - 在 NSuserDefault 中获取 json 结果并在 Swift 中显示 MapKit 中注释的结果

ios - UIScrollView 内的 UIViewControllers 内的 UIbutton 不会在触摸时触发

ios - TableView reloadData 对自定义 dataSource 类不执行任何操作

ios - TableviewCell 中的 CollectionView : Display data using Alamofire and SwiftyJSON with MVC model

ios - 我的 Sprite Kit 按钮在 Swift 中不起作用

swift - 如何对大量入站 CloudKit 通知进行排队