我正在尝试找出一种在到达某个位置时拖动和删除 subview 的方法。到目前为止,我拥有的是一个 View Controller ,我在其中添加了几个 subview 。我的 subview 类是可旋转和可调整大小的,我可以在 View Controller 上移动它们。假设我想将 subview 移动到 View Controller 的顶部中心并将其删除。我的父 View Controller 如何知道 subview 的位置并执行删除? 另一个问题是所有 subview 都是从同一个自定义类生成的。我应该如何定义哪个 subview 是应该删除的 subview ? 预先感谢您。
最佳答案
您可以使用 UIPanGestureRecognizer 来移动 View 和 CGRect.intersects查看新位置是否将您带入删除区域(如果您想要求完全位于删除区域内,请改用 contains):
@IBAction func pan(_ recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
centerXConstraint.constant += translation.x
centerYConstraint.constant += translation.y
viewToMove.offset.x += translation.x
viewToMove.offset.y += translation.y
if viewToMove.frame.intersects(deletionRect) {
//Delete logic here
} else {
viewToMove.setNeedsDisplay()
recognizer.setTranslation(.zero, in: self.view)
}
}
如果您有多个 View ,您可以使用 UIView.tag 或 Set 来确定哪个 View 是哪个 View 。
关于ios - 快速拖动 subview 以删除特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42280614/