Reputation: 956
I have two view controllers. In the first one i have label and 4 buttons representing a color, and a button called next. I want to accomplish that when a user selects a color in the first view controller and clicks next, that the label in my next viewController will automatically have that color.
This is what i have so far but i can't make it work.
import UIKit
class ViewController: UIViewController {
var backGroundColor = UIColor()
@IBOutlet var face: UILabel!
@IBAction func red(sender: AnyObject) {
face.backgroundColor = UIColor.redColor()
}
@IBAction func green(sender: AnyObject) {
face.backgroundColor = UIColor.greenColor()
}
@IBAction func blue(sender: AnyObject) {
face.backgroundColor = UIColor.blueColor()
}
@IBAction func yellow(sender: AnyObject) {
face.backgroundColor = UIColor.yellowColor()
}
@IBAction func next(sender: AnyObject) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("face") as! Face2
vc.newFace.backgroundColor = self.face.backgroundColor
self.navigationController?.pushViewController(vc, animated: true)
}
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.
}
}
// My Face2 class:
import UIKit
class Face2: UIViewController {
var backGroundColor = UIColor()
@IBOutlet var newFace: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// var vc = ViewController()
self.newFace.backgroundColor = backGroundColor
}
}
Upvotes: 0
Views: 132
Reputation: 100
my suggestion is to set a nsstring (string that you set when you press the color button) property to second view controller and in the second view controller view did load make a switch based on the passed string to set the background color
Upvotes: 0
Reputation: 131426
Welcome to SO.
You are making a common design mistake.
Don't try to manipulate the second view controller's views directly. That's bad design, and often doesn't work.
Instead add a property/properties to your Face2 class.
In this case, a backgroundColor
property is probably all you need.
Set that property in your next
function, and then in your Face2 class's viewDidLoad method, use the color to set the background color of whatever views need to use the custom color. If you decide later that the set of views that need to change color is different, you can change the code for your Face2 class and the first view controller doesn't need to change at all.
You also need to get rid of vc2. That makes no sense. You create a new Face2 view controller vc
with a call to instantiateViewControllerWithIdentifier
. That's the one you should be configuring. The one you create in vc2 is never used for anything. It will get deallocated as soon as you exit the next()
function.
Upvotes: 1