Jay Park Jay Park - 8 days ago 6
iOS Question

How to change segmented control title from another UIViewController (Settings)

EDIT
Current Code

So I am just starting iOS development so I decided to make a Tip Calculator to learn the basics and the foundation of Swift. I am 70% way there I feel like however I am having trouble with referencing data from another UIViewController...

This is what my story board looks like.....

So I have the load screen which after I click the button it goes to the Tip Calculator...then I have a settings which can change the titles of the segmented control sections. So if I wanted to change my default settings to (10%, 15%, 30%) I can do that on Settings. However I can not seem to figure out how to do get the TextField.text and making it the title of the Segmented Control title.

This is the code for the Tip Calculator (2nd screen)

I have a class ViewController3 class that belongs to the Settings page but it is completely blank.

Answer

To pass the settings back to your first viewController, you can use a closure that is passed from the first viewController.

Here is an example of how to do this. In prepare(for:) set the closure processTipSettings to point to a handler function. In this case, changeSegmentLabels will take the tip settings and make them the labels of the segmented control.

When the user hits save, the @IBAction for the button will call processTipSettings with the values from the textFieldLabels, and changeSegmentLabels will update the titles in the segmented control.


ViewController.swift:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var tipsSegmentedController: UISegmentedControl!

    func changeSegmentLabels(labels: [String?]) {
        if labels.count == 3 {
            for i in 0..<3 {
                tipsSegmentedController.setTitle(labels[i], forSegmentAt: i)
            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "settings" {
            if let dvc = segue.destination as? SettingsViewController {
                dvc.processTipSettings = changeSegmentLabels
            }
        }
    }

}

SettingsViewController.swift

class SettingsViewController: UIViewController {

    @IBOutlet weak var tip1: UITextField!
    @IBOutlet weak var tip2: UITextField!
    @IBOutlet weak var tip3: UITextField!

    // Call this closure when Save is pressed.
    var processTipSettings: (([String?]) -> ())?

    @IBAction func saveSettings(_ sender: UIButton) {
        processTipSettings?([tip1.text, tip2.text, tip3.text])

        _ = self.navigationController?.popViewController(animated: true)
    }

}