Multiple Outlets Tutorial

Creating Outlets for multiple Objects can be time-consuming and tedious. It is also possible for objects to share the same Outlets. In this tutorial multiple outlets will be created using the tagvalue of the buttons. This Tutorial is made with Xcode 7.2 and built for iOS9.2 and Swift 2.1.

Open Xcode and create a new Single View Application. For product name, use IOS9MultipleOutletsTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the StoryBoard and drag a button from the Object Library to the top-left of the main view. Go to the Attribute Inspector and in the View section change the Tag value to 10.

Copy this button and place it next to the first button in the top-right corner, this button will have the same tag value. Next, drag another button from the Object Library to the main view, place the button below the top-left button. Select the button and go to the Attribute Inspector. In the View section change the Tag value to 20. Again, copy the button and place it on the right side next to this button. The Storyboard should look like this.

Select the main view and select the "Resolve Auto Layout Issues" button on the bottom-right corner of the Interface Builder. Select the "Reset to Suggested Constraint option in the All Views section.


Go to the ViewController.swift file and change the viewDidLoad mehod to

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for subview in view.subviews where subview.tag == 10 {
        let button = subview as! UIButton
        button.addTarget(self, action: "changeColorRed:", forControlEvents: .TouchUpInside)
    }
        
    for subview in view.subviews where subview.tag == 20 {
        let button = subview as! UIButton
        button.addTarget(self, action: "changeColorGreen:", forControlEvents: .TouchUpInside)
    }
}

The subview property can be used to traverse to the subviews of the main view. A target is added to each button. which was set with the tag value.Next, Implement the target methods.

func changeColorRed(sender: AnyObject) {
    let button: UIButton = sender as! UIButton
    button.tintColor = UIColor.redColor()
}
    
func changeColorGreen(sender: AnyObject) {
    let button: UIButton = sender as! UIButton
    button.tintColor = UIColor.greenColor()
}

The color of the button will change when the button is selected. Build and Run the project and click on the buttons to change the colors.

You can download the source code of the IOS9MultipleOutletsTutorial at the ioscreator repository on Github.