iosswiftaddtarget

addTarget adding extra events


I want to add another events when the button is clicked. i use addTarget to observe the button when is clicked and call a method name showModal. see the code below.

headerView.addTaskButton.addTarget(self, action: #selector(showModal), for: .touchUpInside)

and i want to add another action when that button is pressed. but i don’t know where.

self.todoListViewModel.updateMode(.edit)

is there any way to do it with addTarget? like adding closure and stuff?

so i don’t want to put that in showModal method. is there anyway?


Solution

  • You can have 2 actions declared :

    func commonAction(_ sender: UIButton) {
        // code for all buttons
    }
    func showModal(_ sender: UIButton) {
    
        self.todoListViewModel.updateMode(.edit)
        self.commonAction(sender)
    }
    

    Another option : set the tag of the button to know if you must do the action :

    func commonActionOrModal(_ sender: UIButton) {
        If sender.tag == 1 {
            self.todoListViewModel.updateMode(.edit)
        }
        // code for all buttons
    }