Step 5.1: Open the "ViewController.swift" file
In the Xcode project navigator, locate the "ViewController.swift" file. Click on the file to open it in the editor. Step 5.2: Create outlets for the text fields and labels
In the "ViewController.swift" file, add the following code: Swift
import UIKit
class ViewController: UIViewController { @IBOutlet weak var fahrenheitTextField: UITextField! @IBOutlet weak var celsiusLabel: UILabel! @IBOutlet weak var fahrenheitLabel: UILabel! @IBOutlet weak var celsiusTextField: UITextField!}These lines declare four outlets: two for the text fields and two for the labels. Step 5.3: Connect the outlets to the views
Open the "Main.storyboard" file. Select the "ViewController" scene. Click on the "Show Assistant Editor" button (two circles overlapping) or press ⌘+Option+Enter. This will open the "ViewController.swift" file in the assistant editor. Control-click (or right-click) on the "Fahrenheit:" label and drag to the fahrenheitLabel outlet in the code. Repeat this process for the other three views: "Fahrenheit" text field to fahrenheitTextField outlet. "Celsius:" label to celsiusLabel outlet. "Celsius" text field to celsiusTextField outlet. Step 5.4: Create an action for the "Convert" button
In the "ViewController.swift" file, add the following code: Swift
@IBAction func convertToFahrenheit(_ sender: UIButton) { // Conversion logic will go here}This declares an action method for the "Convert" button. Step 5.5: Connect the action to the "Convert" button
Open the "Main.storyboard" file. Select the "Convert" button. Control-click (or right-click) on the button and drag to the convertToFahrenheit action in the code. Release the mouse button to connect the action. That's it! You've successfully created outlets for the views and connected them to the code, and also created an action for the "Convert" button.
Now, you can implement the conversion logic in the convertToFahrenheit method, as I mentioned earlier:
Swift
@IBAction func convertToFahrenheit(_ sender: UIButton) { guard let fahrenheit = Double(fahrenheitTextField.text!) else { return } let celsius = (fahrenheit - 32) * 5/9 celsiusLabel.text = "\(celsius)"}This code will be executed when the user clicks the "Convert" button.