Yuuu
Yuuu

Reputation: 879

Swift addTarget to a button and call function in different View Controller file from UIview file

now I practice applying the MVC pattern in my Swift project. I have one View Controller (VC) file and one UIView file.

In the VC file, I added the UIView file like below.

class MyViewController: UIViewController {
    private var myView = MyView()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(myView)
        myView.frame = CGRect(origin: .zero, size: view.bounds.size)
        // and other codes...
    }

    @objc func showDeleteAlert() {
        print("showDelete is pressed")
    }
}

Then, inside the UIView file, I added some views and buttons (I just copy the button part).

class MyView: UIView {
    lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.setTitle("delete", for: .normal)
        button.addTarget(target: MyViewController, action: #selector(showDeleteAlert), for: UIControl.Event.touchUpInside) // -> I get error in here saying "Cannot find 'showDeleteAlert' in scope"

        return button
    }()

// and more codes...
}

What I want to do here is how to set the target to showDeleteAlert function when the deleteButton is pressed?

I saw tutorials add "self" as a target argument, but in my case, I separated view and controller so not really sure how to access the function in MyViewController.

Thank you...

Upvotes: 3

Views: 2379

Answers (1)

Phil Dukhov
Phil Dukhov

Reputation: 88497

You have two options here:

  1. move addTarget into view controller viewDidLoad:
myView.deleteButton.addTarget(self, action: #selector(showDeleteAlert), for: UIControl.Event.touchUpInside)
  1. If you wanna make button private(which is a good practice), you can add proxy func to your MyView
func addDeleteButtonTarget(_ target: Any?, action: Selector) {
    deleteButton.addTarget(target, action: action, for: .touchUpInside)
}

And call it:

myView.addDeleteButtonTarget(self, action: #selector(showDeleteAlert))

In any case, you cant call button.addTarget(target: MyViewController, ...), because you need to pass an instance of the MyViewController, not just a class name.

Upvotes: 9

Related Questions