addTarget adding extra events

148 Views Asked by At

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?

  • I want only addTaskButton to update the mode. if i added self.todoListViewModel.updateMode(.edit) in showModal method, everything calling that method will be updated the mode as .edit

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

2

There are 2 best solutions below

0
Ptit Xav On BEST ANSWER

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
}
1
Kishan Barmawala On

You don't need to add another action, just place your code in "showModal" function

func showModal(_ sender: UIButton) {
   
   self.todoListViewModel.updateMode(.edit)

   // your remaining code

}