在 Swift 中以编程方式模拟滑动手势 [英] programmatically simulate a swipe gesture in Swift

查看:33
本文介绍了在 Swift 中以编程方式模拟滑动手势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个用于在 Swift 中滑动的手势识别器.我希望能够模拟卡片的投掷(以编程方式滑动视图).

I am implementing a gesture recognizer for swiping in Swift. I wan to be able to simulate the flinging of the card (programmatically swipe the view).

我以为会有一个内置函数,但我发现的只是点击手势而不是滑动手势.

I assumed there would be a built in function for this but all I have found is one for tap gesture not swipe gesture.

这就是我实现滑动手势的方式:

This is how I am implementing the swipe gesturing:

  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)

推荐答案

以下是可用于以编程方式滑动单元格的代码.执行时,单元格将动画到滑动位置.

Here is code you can use to programatically swipe the cell. When performed, the cell will animate to the swiped position.

@IBAction
func swipeFirstCell() {
    if let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) {
        tableView.perform(Selector("_endSwipeToDeleteRowDidDelete:"), with: nil) // cancel any existing swipes
        tableView.perform(Selector("_swipeToDeleteCell:"), with: cell)
    }
}

请注意,您还需要为 canEditRowAtIndexPath 中的单元格返回 true.

Note you need to also return true for the cell from canEditRowAtIndexPath.

这可能会被 Apple 的私有 API 检测标记,但您至少可以将其用于开发,如果您真的这样做,还可以混淆字符串.

This might get flagged by Apple's private API detection but you can at least use it for development and perhaps obfuscate the string if you really to.

这篇关于在 Swift 中以编程方式模拟滑动手势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆