Title: Use variables from the viewDidLoad in a button action in the UIviewcontroller
Tags: swift
Question: I am trying to make a button display an alert depending on the text of the button. So in the view did load I have some random values I am pulling from arrays:
let ingredient1 = realBases[Int(arc4random_uniform(UInt32(realBases.count)))]
var ingredient2 = juices[Int(arc4random_uniform(UInt32(juices.count)))]
let indexOf2 = juices.index(of: ingredient2)
juices.remove(at: indexOf2!)
if ingredient2 == ingredient1 {
ingredient2 = ""
var ingredient3 = juices[Int(arc4random_uniform(UInt32(juices.count)))]
let indexOf3 = juices.index(of: ingredient3)
juices.remove(at: indexOf3!)
if ingredient3 == ingredient1 {
ingredient3 = ""
var ingredient4 = juices[Int(arc4random_uniform(UInt32(juices.count)))]
let indexOf4 = juices.index(of: ingredient4)
juices.remove(at: indexOf4!)
if ingredient4 == ingredient1 {
ingredient4 = ""
As you can see, after the valueis set, that element is deleted from the array to prevent that it is reused.
Then I give the buttons those names:
btnO1.setTitle(newArray[0], for: UIControlState.normal)
btnO2.setTitle(newArray[1], for: UIControlState.normal)
btnO3.setTitle(newArray[2], for: UIControlState.normal)
btnO4.setTitle(newArray[3], for: UIControlState.normal)
btnO5.setTitle(newArray[4], for: UIControlState.normal)
Now I want the buttons to display specific messages, depending on the name they acquired . That is, if a button got the name Oat Milk, when clicked, I would like that information about oats is displayed in an alert.
So I have the following code:
let ingredient1Text = UIAlertController.init(title: "", message: "", preferredStyle: UIAlertControllerStyle.alert)
ingredient1Text.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:nil))
self.present(ingredient1Text, animated: true, completion: nil)
switch ingredient1 {
case "Oat Milk":
ingredient1Text.title = "Oat Milk"
ingredient1Text.message = oatMilkText
case "Soy Milk":
ingredient1Text.title = "Soy Milk"
ingredient1Text.message = soyMilkText
case "Almond Milk":
ingredient1Text.title = "Almond Milk"
ingredient1Text.message = almondMilkText
case "Cashew Milk":
ingredient1Text.title = "Cashew Milk"
ingredient1Text.message = cashewMilkText
What I cant do, is put that code in the button action. That is because the variable ingredient1 is in the viewDidload(), so it doesn't recognize the variable. I could put those variables outside of the viewDidLoad, but I cant because I am removing elements from the array after defining each random value, and apparently this cannot happen at a top level.
So I am trapped.
Comment: Maybe the answers help. Still, *why* are you deleting the `ingredient` values? (1) Seems like poor design to me. (2) Just store them in an array *and* associate their index value with the `tag` value of the `UIButton`. That's a *much* better design and really doesn't take up any more of a "footprint". It's not 2008 (or for us real old-timers, 1978) where we need to care about how many bytes or bits something like this uses. Just do it right!


Here is another answer: You can access the button's title in the action like so:
@IBAction func myAction(_ sender: Any?) {
guard let button = sender as? UIButton else { return }
let buttonTitle = button.title(for: .normal)
...

Here is another answer: Add a dictionary as a new member to your class like this:
var titleToActionDictionary: [String : String]
Now, in viewDidLoad add items to titleToActionDictionary like this:
titleToActionDictionary[newArray[0]] = message // Message is the message you want to show in the alert of the button that has the title newArray[0]
And so on.
Now, your button's action should look like this:
@IBAction func myAction(_ sender: UIButton?) {
let alertMessage = self. titleToActionDictionary[sender.title(for: .normal)]

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:09/03/17', 'FavoriteCount': 0.0, 'PostTypeId': 1, 'Tags': '<swift>', 'Title': 'Use variables from the viewDidLoad in a button action in the UIviewcontroller', 'ViewCount': 238, 'id': 46028486, 'user_AboutMe': '', 'user_AccountId': 11472488.0, 'user_DisplayName': 'Arjuna Deva', 'user_Reputation': 265.0, 'user_Views': 48.0, 'user_id': 8408861.0}}