Search code examples
iosswiftuikitselectoruitapgesturerecognizer

Changing two objects in the selector method for button target Swift


let buttonArray: [UIButton] = [UIButton]()
let labelArray: [UILabel] = [UILabel]()

// Inside some function

func {
 // Create these UI
  for (index, num) in numberOfButtonsNeeded.enumerated() {
   let button = UIButton()
    button.tag = index
    button.addTarget(self, action: #selector(self.tap(sender:)), for: .touchUpInside)
    buttonArray.append(button)
   
   let label = UILabel()
   label.text = "hi"
   labelArray.append(label)

  }
}

... 

@objc func tap(sender: UIButton) {
   sender.setImage(UIImage(named:"likeImage"))
 
}

I am currently creating like buttons and a label to show the number of like that comment has. The number of this button and label obviously depend on the number of the comment from the database, so I programmatically create these button and labels once the data is loaded.

However, when I press the like for the button, I need the label to also change as well. For the button target, we have a selector method called "Tap" that takes in the button as the sender. However, I also need to increment/decrement the label as well. Is there a way the selector method can take both the button and the label as parameters?

I tried doing

@objc func tap(sender: UIButton) {
   sender.setImage(UIImage(named:"likeImage"))
   labelArray[sender.tag].text = <The incremented number> 
}

But only the button image would change and the label would not get updated.


Solution

  • Is there a way the selector method can take both the button and the label as parameters?

    No, there is not. However, your impulse at the end of the question is almost what I do. No need for an array, just give the button-label pairs matching tags, like 1 and 101, 2 and 102, and so on. Now look at the sender's tag, add 100, call view(withTag:) to find the label, cast down to a label, and you're all set.