UIViewController can communicate with its UIView directly using Action and Outlet connections.
Let's have a look the Action and Outlet in working by creating a new Single View App and call ActionAndOutletDemo.
Once the project is created, add one label and one button as shown below.
Let's hide the left and right panels, select the storyboard and then switch to the Assistant mode.
Hold the Control key down, then click on the label and drag over to your ViewController class and release the mouse above any existing methods. Now you will see a small pop up where the Connection is set to an outlet. Let's give it a name myLabel and click Connect button.
Next, go to the button in the storyboard, hold the control button again, click the button and drag over below where we have created the basicLabel.
This time when the pop-up appears, make sure to change the Connection from an outlet to action. Give it a name changeText. Now our ViewController class have the following additional lines of code. One is the outlet, and the other one is the action.
@IBOutlet weak var myLabel: UILabel!
@IBAction func changeText(_ sender: Any) {
}
myLabel
to change the text of that label.@IBOutlet
and @IBAction
.Let's add the following line of code to change the text of a label when the button is tapped.
myLabel.text = "New Text"
Now the ViewController class will look like this.
//
// ViewController.swift
// ActionAndOutletDemo
//
// Copyright � 2018 ZZZ Projects. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myLabel: UILabel!
@IBAction func changeText(_ sender: UIButton) {
myLabel.text = "New Text"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Run your application
Now when you click the button, it will change the text of the label.