问题
I know how to set UIPanGesture events and recognizers and get the data I need when I create them programatically.
However I am trying to learn how to work with the storyboard and use IBOutlets.
I have dragged over an IBAction for 'Touch Drag Inside'.
@IBAction func dragButtonDragEvent(sender: AnyObject)
{
println(sender)
}
The problem is the sender object I get is just the button itself.
Is there a way to get the drag distance or drag event data when using an IBAction?
I tried
@IBAction func dragButtonDragEvent(sender: AnyObject)
{
var drag:UIPanGestureRecognizer = sender as UIPanGestureRecognizer
println(drag.state)
}
But I get a bad memory access error and the println is not executed as the sender is the button NOT the event.
Can you suggest how to use Touch Drag Inside events when connecting from a Storyboard?
回答1:
Create the @IBAction function with an event parameter like this:
@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))
}
}
This will println the user's touch location on the button as they drag their finger across the button. You can then use the first point and last point to get the distance.
Please note, if you're modifying the method signature of the existing function, then you'll have to reconnect it in the storyboard.
回答2:
Change the arguments of IBAction to "Sender and Event".
来源:https://stackoverflow.com/questions/27469731/get-touch-drag-inside-distance-when-setting-ibaction-from-storyboard