Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 Draggable UIButton

Apologies as I'm still learning the basics of Swift.

I'm trying to move a button when I drag it which sounds simple. I can't figure out how to pass along the sender information to the drag function so I can associate it with the button that is being dragged.

I create multiple one word buttons which are only text and attach a pan gesture recognizer to each of them:

let pan = UIPanGestureRecognizer(target: self, action: #selector(panButton(_:)))
let word = UIButton(type: .system)
word.addGestureRecognizer(pan)

I've created this function to trigger when the button is moved:

func panButton(sender: UIPanGestureRecognizer){
    if sender.state == .began {
        //wordButtonCenter = button.center // store old button center
    } else if sender.state == .ended || sender.state == .failed || sender.state == .cancelled {
        //button.center = wordButtonCenter // restore button center
    } else {
        let location = sender.location(in: view) // get pan location
        //button.center = location // set button to where finger is
    }
}

I'm getting the following error:

Use of unresolved identifier 'panButton'
like image 889
Alex Bailey Avatar asked Feb 05 '23 05:02

Alex Bailey


1 Answers

First of all, your action needs to be a selector in Swift 3. So that would look something like this:

let pan = UIPanGestureRecognizer(target: self, action: #selector(panButton(_:))

Also, you can't pass the value of a button through a selector, so you would need to change your func to be:

func panButton(sender: UIPanGestureRecognizer){
    ...
}

If you're wondering how you are supposed to find the button if you can't pass it as a parameter, then you might consider using tags.

like image 152
Benjamin Lowry Avatar answered Mar 12 '23 04:03

Benjamin Lowry