Tags (for multiple UI elements)

Adding code to multiple buttons and manually adding code to button
Creating multiple outlets

1. Select a button
2. Go to attributes inspector, view.
3. Give it a tag number, for instance, 1
4. Give the next button another tag.
5. Go to ViewController.swift
6: type:

@IBAction func numberClicked(_ sender: UIButton) {}

7. Go back to storyboard.
8. Click on button and press control. Connect it to the ViewController button (yellow circle with square in the middle).
9. Select the function that you have created above. This connects the button to the code. Do the same for the other buttons that you wish to connect to the code.

Adding the code using the tag:

10. In the function created:

switch sender.tag
{
 case 0: print("0")
 case 1: print("1")
 default: return
}

Notes:
If you change the arguments or names of the function, you will need to reassign the buttons to the function. In addition, you will need to right click View Controller in storyboard and delete all the events with the ! next to it, else you will get the error:


libc++abi.dylib: terminating with uncaught exception of type NSException

Reference button based on its tag
for p in 5..<10
{
//from tags 5 to 10
if let btn = self.view.viewWithTag(p) as? UIButton
{
 btn.backgroundColor = UIColor.clear
}
}

Comments

Popular posts from this blog

Setting up a playground

Go to another page