I am trying to change a picture and a label programmatically.
Here's the current code setup:
#IBOutlet weak var image: UIImageView!
#IBOutlet weak var label: UILabel!
override func viewDidLoad(){
super.viewDidLoad()
setlabel()
setImage()
}
func setImage(){
self.image.image = UIImage(named: name)
}
func setlabel(){
self.label.text = string
}
But unfortunately, I'm receiving nil for both UI elements, the label and the image. I've doublechecked the connection between my storyboard and the variables- they are set correctly, imho. They are available, since I am calling them outside the viewDidLoad function.
Anyone any suggestion?
Regards
I found the solution. I had 2 views- let's call them A and B.
A contained a button- and the button had 2 functions: Change the view and set the labels/images. Those functions were defined in the Controller of view A.
Since I wanted to change the labels and images of view B, I got the exception.
I had to include another Controller and transfer the functions for setting the images and labels to Controller B. Voila, I could change the images and labels.
Summarized: I had the right connections and the right functions, but in the wrong place.
Thank you all!
Related
Why when I pass data to a UILabel directly in the Second View Controller it turns to be nil but when I pass data to a variable first and then apply it to the UILabel everything works fine?
The following code crash the app after segue performed (theResult is nil):
Second View Controller:
#IBOutlet weak var theResult: UILabel!
Main View Controler:
secondVC.theResult.text = “Nice”
But when I create a variable in the Second View Controller, I can pass the data to it easily and then apply it to the UILabel without any problem:
Second View Controller:
var calculation: String?
#IBOutlet weak var theResult: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
theResult.text = calculation
}
Main View Controler:
secondVC.calculation = “Nice”
Why is that?
Note: The UILabel has a default value already when it is created in the Storyboard.
I am almost sure that this is not working but I want to know the reason. Why you can easily change for example the background of the Second View Controller like this:
secondVC.view.backgroundColor = .green
but when you touch the IBOutlets it do not work.
I'm following official iOS Apps tutorial to make a basic Single View Application in Xcode.
Literally all we have done so far is:
Added a label to the UI and set initial text to 'Meal name:'
Added a textbox to the UI
Added a button to the UI
Then we've added some very simple code to the View Controller declaring the label as an outlet and a button action which, when invoked, should change the label's text to Default Text.
My ViewController code is now identical to the tutorial code namely:
class ViewController: UIViewController {
//MARK: Properties
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var mealNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//MARK: Actions
#IBAction func setDefaultLabelText(_ sender: UIButton) {
mealNameLabel.text = "Default Text"
}
}
The problem is that when I press the button in simulator, I get an error message saying an implicitly unwrapped optional value is nil. (app launches fine, it's just when pressing the button)
As I understand it this means something is blank that can't be, but the only optionals I have are:
The textbox, which isn't blank because before I press the button I write 'biscuits' or something in it
The label text, which isn't blank because it's set to 'Meal name:' by default
I really can't work out what supposedly has a nil value that is triggering this error?
As I understand it this means something is blank that can't be
No , This means you need to make sure outlet
mealNameLabel.text = "Default Text" // here mealNameLabel is nil
is connected to the label in IB
I have created a standard outlet for a view that will hold different information based on the button selected on the previous screen.
#IBOutlet weak var labelView: UIView!
It shows it is connected in both the story board view and on the code itself, however, every time I get to any reference to the labelView such as:
if detail.description == "About"
{
labelView.backgroundColor = UIColor.red
}
Then the app crashes out with:
fatal error: unexpectedly found nil while unwrapping an Optional value
I have tried everything I can think of or read on the internet:
Removed and replaced the connection
Deleted the derived data folder like one post suggested
Created a reference to self.view to force it to load
Moved it to viewDidAppear
Moved it to viewWillAppear
Moved it to viewDidLoad (which is where it is currently being
called)
I am sure at this point that the answer is rather simple and I am just completely missing it.
To see where the outlet is being set to nil, try this:
#IBOutlet weak var labelView: UIView? {
didSet {
print("labelView: \(labelView)")
}
}
You should see it set to an initial value when the view is loaded. If it then gets set to nil, put a breakpoint on the print and your should be able to see from the backtrace where it's happening.
Views are lazy initialized. In case you are calling the affected line of code before viewDidLoad() in the views life cycle, try to access viewin advance:
if detail.description == "About" {
_ = self.view
labelView.backgroundColor = UIColor.red
}
I created a navigation controller with a view controller inside, containing a label. This label should be changed, when the view controller is loaded on tapping a button.
class ViewController: UIViewController {
#IBOutlet weak var btnEmergency: UIButton!
override func viewWillAppear(animated: Bool) {
self.btnEmergency.backgroundColor = UIColor.redColor();
}
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func btnEmergencyTapped(sender: AnyObject) {
let emergencyViewController = storyboard?.instantiateViewControllerWithIdentifier("EmergencyViewController") as! EmergencyViewController
emergencyViewController.emergencyLabel?.text = "Notruf"
navigationController?.pushViewController(emergencyViewController, animated: true)
}
}
But the label text does not change when loaded. I am relatively new to SWIFT so I try to learn my ropes at the moment using optionals. So I guess the reason is, that the label is not yet instantiated when the view is being loaded on pressing the button. Therefore the default text is being shown and not the text I want to have appear on screen.
I am a little bit stuck at the moment, how to correctly change the label text, when this is an optional. So I guess I cannot expect the label to be there, when I call it. But how do I handle this correctly?
Instead of this, the correct way is to set a property of your emergencyViewController.
In your emergencyViewController viewDidLoad set your label text according to the property set previously.
Anything that you do between initialize of a viewController to viewDidLoad will not take effect.
What happens to your “fromView” after you use UIView.transitionFromView? How do you get it back? (re-initialize it?).
Here’s a simple example I made and get “fatal error: unexpectedly found nil while unwrapping an Optional value” when I try to get back to the “fromView” or reference a label on it, etc.
Let’s say I’ve set these views in my storyboard - I added a subview to the root called “cardView” and then 2 views under cardView called “backView” and “frontView"
Linked these up to the view controller and linked the Flip button to an action that looks like this (along with the variables):
#IBOutlet weak var backView: UIView!
#IBOutlet weak var frontView: UIView!
#IBOutlet var cardView: UIView!
var front = true
#IBAction func flipIt(sender: AnyObject) {
if front {
UIView.transitionFromView(self.frontView, toView: self.backView, duration: 1, options: UIViewAnimationOptions.TransitionFlipFromRight, completion: nil)
} else {
UIView.transitionFromView(self.backView, toView: self.frontView, duration: 1, options: UIViewAnimationOptions.TransitionFlipFromLeft, completion: nil)
}
front = !front
}
So when I run this - the first tap of the “Flip” button does fine, it flips over to the backView, but then when I tap it again I get “fatal error: unexpectedly found nil while unwrapping an Optional value” on the 2nd transitionFromView line (the one under “else”).
Obviously there’s some effect of transitionFromView that I don’t understand. I've tried a lot of different things, including a tutorial that uses this transition and was able to get it working but it doesn’t use the storyboard so I’m not sure how to apply how that tut does it to my storyboard views, apparently...
thanks for any help.
You've declared your view properties as weak, so they're getting released as soon as it appears they're no longer needed. Just change them to strong (by removing "weak") and you should be golden:
#IBOutlet var backView: UIView!
#IBOutlet var frontView: UIView!