edoriggio
edoriggio

Reputation: 331

Using a nested function as the selector of an action - swift

This is my code:

func didSelectLabel() {

    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 30))

    label.center = viewForEdit.center
    label.textAlignment = .center
    label.isUserInteractionEnabled = true

    func userDragged(gesture: UIPanGestureRecognizer) {

        let loc = gesture.location(in: self.viewForEdit)
        label.center = loc

    }

    gesture = UIPanGestureRecognizer(target: self, action: userDragged(gesture:))
    label.addGestureRecognizer(gesture)

    let alert = UIAlertController(title: "Write your text", message: "", preferredStyle: .alert)
    let continueAction = UIAlertAction(title: "Continue", style: .default) { (UIAlertAction) in

        label.text = alert.textFields?[0].text

    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    alert.addTextField { (textField) in

        textField.placeholder = "Write here"

    }

    alert.addAction(continueAction)
    alert.addAction(cancelAction)

    present(alert, animated: true, completion: nil)

    self.viewForEdit.addSubview(label)

}

I would like to use

func userDragged(gesture: UIPanGestureRecognizer)

as the selector of

gesture = UIPanGestureRecognizer(target: self, action: userDragged(gesture:))

The problem is that if I run the code it crashes saying

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TestApp.ViewControllerEditor userDragged:]: unrecognized selector sent to instance 0x7fc6b3c282b0'

P.S. I cannot put the function 'userDragged(gesture:)' outside of the function 'didSelectLabel()' becuse if I do so 'label.center = loc' returns an error. This is because 'label' is called inside of the function 'didSelectLabel()'

Upvotes: 0

Views: 97

Answers (1)

raver
raver

Reputation: 283

The easiest way is to move your function outside didSelectLabel, and change it to:

func userDragged(gesture: UIPanGestureRecognizer) {
    let loc = gesture.location(in: self.viewForEdit)
    let label = gesture.view as? UILabel
    label?.center = loc

}

Upvotes: 2

Related Questions