In this app, I'm looking to allow the user to change the background colour of the main menu. within the MenuVC, the user will click on a button labelled, "Choose a colour". A 'ColorPickerVC' will present from a XIB file, modally.
I created an @IBAction for this and contains the following code:
@IBAction func colorPickerPressed = (_ sender: Any) {
let colorPicker = ColorPickerVC()
colorPicker.modalPresentationStyle = .custom
present(colorPicker, animated: false, completion: nil)
}
The colour picker loads modally from a XIB file and displays 9 colours (UIButton) in a grid format.
When the users taps a colour, the background of the ColorPickerVC changes to the that colour:
@IBAction func tile1(_ sender: Any) {
view.backgroundColor = tile1Color.backgroundColor
The user then taps a 'Confirm' button, this dismisses the view and returns to the MenuVC:
@IBAction func confirmBtnPressed(_ sender: Any) {
dismiss(animated: false, completion: nil)
}
Here's what i'm struggling with: During the 'ConfirmBtnPressed' action, I would like the MenuVC background colour to also change to what the ColorPickerVC background is (The colour the user selected earlier)
Any ideas on how to achieve this?
Thanks, Scott
You should learn about the delegate pattern:
First create a protocol that defines the desired function:
protocol ColorPickerProtocol: class {
func didSelectColor(_ color: UIColor)
}
Extend your ViewController with that protocol and implement the method:
class BackgroundColorViewController: UIViewController, ColorPickerProtocol {
func didSelectColor(_ color: UIColor) {
view.backgroundColor = color
}
}
Inside your Xib create a way to pass the delegate and call the didSelectColor function on the desired buttonPress:
class ColorPickerXib {
weak var delegate: ColorPickerProtocol?
@IBAction func dismissButtonPressed(_ sender: UIButton) {
delegate?.didSelectColor(color)
self.dismiss()
}
}
And finally instantiate your Xib in your ViewController with the proper delegate and show it:
let colorPicker = ColorPickerXib()
colorPicker.delegate = self
// Show Xib