I’m working on an app that currently has 2 view controllers.
Within the second viewcontroller, (which I’m using for settings) I use a segement control in order to determine the game’s difficulty. The settings viewcontroller’s purpose is to make changes to the main viewcontroller labels.
The problem I’m having is that I can’t find a way to bring the selected index value of the segment control from the second viewcontroller to the main one.
here’s the settings screen view controller:
public class SettingsScreen: UIViewController {
@IBOutlet weak var levelPick: UISegmentedControl! // need to use this
@IBOutlet weak var operationPick: UISegmentedControl!
public override func viewDidLoad() {
super.viewDidLoad()
}
}
and the main:
class MainScreen: UIViewController {
@IBOutlet weak var displayText: UILabel!
public override func viewDidLoad() {
super.viewDidLoad()
}
// how it should work:
func setLevel() {
switch SettingsScreen().levelPick.selectedSegmentIndex {
// easy
case 0:
displaytext.text = "test1"
// medium
case 1:
displaytext.text = "test2"
// hard
case 2:
displaytext.text = "test3"
default:
break
}
}
@IBAction func Roll(_ sender: UIButton) {
setLevel()
}
}
3
Answers
You can use the Delegate pattern or the Closure Callback pattern.
like this:
** SettingsScreen:**
** MainScreen:**
Try a different approach. Instead of trying to figure out the selected index in your main controller, you could directly update the labels of the main controller from the settings controller. You can use NSNotification to achieve this.
In your main controller viewDidLoad:
In settings controller in your UISegmentedControl’s value changed event:
Since you’re referring to a referencing a user specified
SegmentedIndex
based on some setting changes, you could utiliseUserDefaults
to store that index for later retrieval. This would be Simpler but it also depends on what you’re actually after.Then in your MainScreen code