ios - 从 Storyboard 设置 IBAction 时获取 'Touch Drag Inside' 距离

标签 ios xcode events swift uistoryboard

我知道如何设置 UIPanGesture 事件和识别器,并在我以编程方式创建它们时获取我需要的数据。

不过,我正在努力学习如何使用 Storyboard 和使用 IBOutlets。

我已经为“Touch Drag Inside”拖过一个 IBAction。

@IBAction func dragButtonDragEvent(sender: AnyObject)
    {
        println(sender)
    }

问题是我得到的发送者对象只是按钮本身。

有没有办法在使用 IBAction 时获取拖动距离或拖动事件数据?

我试过了

@IBAction func dragButtonDragEvent(sender: AnyObject)
    {
        var drag:UIPanGestureRecognizer = sender as UIPanGestureRecognizer
        println(drag.state)
    }

但是我遇到了错误的内存访问错误,并且 println 没有执行,因为发送者是按钮而不是事件。

您能建议如何在从 Storyboard连接时使用 Touch Drag Inside 事件吗?

最佳答案

使用这样的事件参数创建@IBAction 函数:

@IBAction func touchDragInsideAction(sender: AnyObject, event: UIEvent) {
    // if the sender is a button
    if let button = sender as? UIButton {
        // get the touch inside the button
        let touch = event.touchesForView(button)?.anyObject() as UITouch
        // println the touch location
        println(touch.locationInView(button))
    }
}

当用户将手指拖过按钮时,这将打印用户在按钮上的触摸位置。然后,您可以使用第一个点和最后一个点来获取距离。

请注意,如果您要修改现有函数的方法签名,则必须在 Storyboard中重新连接它。

关于ios - 从 Storyboard 设置 IBAction 时获取 'Touch Drag Inside' 距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27469731/

相关文章:

如果不重新启动应用程序,iOS storyBoard 本地化将无法工作

ios - xcode 5 上的 Inspector size 没有显示任何内容

c++ - Qt 每当按下时进入 QTextEdit

javascript - 嵌套两个 Javascript 事件

ios - Clang GCC 扩展 - 括号中的 block 返回一个值

ios - 参数类型不符合 Encodable

android - 如何将用户从移动应用程序重定向到移动网络浏览器?

xcode 7.3 UI测试随机通过或失败

xcode - Swift "guard let"解包失败

c# - WPF C# PreviewDrop/Drop 事件未触发(使用 dragadorner)