I have these functions:
private func chooseOfferButton1Tapped() {
let vc = ChooseRdvVC()
vc.offerCatched = arrayCatched![0]
HapticsManager.shared.vibrate(for: .success)
navigationController?.pushViewController(vc, animated: true)
}
private func chooseOfferButton2Tapped() {
let vc = ChooseRdvVC()
vc.offerCatched = arrayCatched![1]
HapticsManager.shared.vibrate(for: .success)
navigationController?.pushViewController(vc, animated: true)
}
...
up to:
...
private func chooseOfferButton50Tapped() {
let vc = ChooseRdvVC()
vc.offerCatched = arrayCatched![49]
HapticsManager.shared.vibrate(for: .success)
navigationController?.pushViewController(vc, animated: true)
}
Here’s how I call the functions:
let index = "chooseOfferButton(oneViewSize)Tapped"
chooseOfferButton.addTarget(self,
action: Selector(index),
for: .touchUpInside)
where oneViewSize
is the number that changes
I’m looking for a way to avoid writing this same function over and over only with 2 numbers changing. How can I use a string in a function name? Or a for loop? Or is there another way? Any help is appreciated.
2
Answers
If you are using table view then you need to use the
tag
property ofUIButton
in yourcellForRowAt indexPath
methodOr if you are using
@IBOutletCollection
then you need to set the tag for each button and set same button click action for each buttonAs mentioned by others there’s only one action needed. The index is passed through the
tag
property of the button.Instead of putting the index into the selector assign the index (aka
oneViewSize
) to thetag
On the callee side get the index from the button (the
sender
)Ans please declare
arrayCatched
non-optional as you force unwrap it anyway