我正在 Swift 中实现用于滑动的手势识别器。我希望能够模拟卡片的抛掷(以编程方式滑动 View )。
我假设会有一个内置函数用于此,但我发现的只是一个用于点击手势而不是滑动手势的函数。
这就是我实现滑动手势的方式:
let gesture = UIPanGestureRecognizer(target: self, action: Selector("wasDragged:"))
cardView.addGestureRecognizer(gesture)
cardView.userInteractionEnabled = true
}
func wasDragged (gesture: UIPanGestureRecognizer) {
let translation = gesture.translationInView(self.view)
let cardView = gesture.view!
// Move the object depending on the drag position
cardView.center = CGPoint(x: self.view.bounds.width / 2 + translation.x,
y: self.view.bounds.height / 2 + translation.y)
最佳答案
您无法模拟手势识别器的全部含义(我的意思是,您实际上无法让 iOS 认为这是一个真实的用户操作)。
但是,您可以欺骗自己的代码,使其表现得就像真正的滑动一样。为此,您需要先创建一个手势识别器:
var gestureRecognizerSwipeRight = UISwipeGestureRecognizer(target: self, action: "activatedGestureRecognizer:")
gestureRecognizerSwipeRight.direction = UISwipeGestureRecognizerDirection.Right
yourView.addGestureRecognizer(gestureRecognizerSwipeRight)
然后将其直接传递给您的操作:
// Some other place in your code
self.activatedGestureRecognizer(gesture: gestureRecognizerSwipeRight)
你的 activatedGestureRecognizer(gesture:)
方法应该是这样的:
func activatedGestureRecognizer(gesture: UIGestureRecognizer) {
if let gestureRecognizer = gesture as? UIGestureRecognizer {
// Here you can compare using if gestureRecognizer == gestureRecognizerSwipeRight
// ...or you could compare the direction of the gesture recognizer.
// It all depends on your implementation really.
if gestureRecognizer == gestureRecognizerSwipeRight {
// Swipe right detected
}
}
}
公平地说,我看不到这样做有任何真正的好处。简单地执行与滑动相关的 Action 而不是实际模拟手势识别器应该好得多。
例如,如果您需要在刷卡时为卡片设置动画,为什么不简单地禁用卡片 View 上的用户交互并以编程方式为其设置动画?
关于ios - 以编程方式模拟 Swift 中的滑动手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38953511/