Reputation: 3441
I am trying to drag a button from one position to other using UITouch. But I'm not able to drag it . I'm facing problem in adding button target...
My code-
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let btn_swap = UIButton.buttonWithType(UIButtonType.Custom) as UIButton!
btn_swap .setTitle("Drag Me", forState: UIControlState.Normal)
btn_swap.backgroundColor = UIColor.yellowColor()
btn_swap.addTarget(self, action: "wasDragged:", forControlEvents: UIControlEvents.TouchDragInside)
btn_swap.frame = CGRectMake((self.view.bounds.size.width - 100)/2.0,
(self.view.bounds.size.height - 50)/2.0,
100, 50)
self.view.addSubview(btn_swap)
self.creation_of_btn()
}
func wasDragged (buttn : UIButton, event :UIEvent)
{
var touch : UITouch = event.touchesForView(buttn) . anyObject() as UITouch
var previousLocation : CGPoint = touch .previousLocationInView(buttn)
var location : CGPoint = touch .locationInView(buttn)
var delta_x :CGFloat = location.x - previousLocation.x
var delta_y :CGFloat = location.y - previousLocation.y
buttn.center = CGPointMake(buttn.center.x + delta_x,
buttn.center.y + delta_y);
}
Upvotes: 5
Views: 5719
Reputation: 1
Swift 4.2
func wasDragged (buttn : UIButton, event :UIEvent){}
btn_swap.addTarget(self,action: #selector(wasDragged(buttn:event:)),for: .touchDragInside)
Upvotes: 0
Reputation: 5340
Event TouchDragInside also needs event argument needs to be passed as the second argument.
Swift 1 :
https://stackoverflow.com/a/24547115/5078763
Swift 2 :
btn_swap.addTarget(self,action: #selector(wasDragged(_:event:)),forControlEvents: .TouchDragInside)
func wasDragged(btnVar : UIButton, evtVar :UIEvent)
{
let touch : UITouch = (evtVar.touchesForView(btnVar)?.first)! as UITouch
let previousLocation : CGPoint = touch .previousLocationInView(btnVar)
let location : CGPoint = touch .locationInView(btnVar)
let delta_x :CGFloat = location.x - previousLocation.x
let delta_y :CGFloat = location.y - previousLocation.y
btnVar.center = CGPointMake(btnVar.center.x + delta_x,
btnVar.center.y + delta_y);
}
Upvotes: 0
Reputation: 42977
You given a wrong selector for your button wasDragged:
. Since your action method look's like
func wasDragged (buttn : UIButton, event :UIEvent)
{
}
slector should be wasDragged: event:
.
btn_swap.addTarget(self, action: "wasDragged:event:", forControlEvents: UIControlEvents.TouchDragInside)
Upvotes: 10