0

I have the following problem. I want to set a special picture in an UIImageView depending on the logged in user.

I have the UIImageView on the Storyboard and created also the Label in ViewController.

My code is the following:

@IBOutlet weak var LabelImage: UIImageView!

let TTC:UIImage = UIImage(named: "TT_C.png")!
let TTV:UIImage = UIImage(named: "TT_V.png")!
let TTT:UIImage = UIImage(named: "TT_T.png")!
let TTR:UIImage = UIImage(named: "TT_R.png")!
let TTM:UIImage = UIImage(named: "TT_M.png")!

if user == "Hannes" {
    LabelImage = UIImageView(image: TTC)
    self.view.addSubview(LabelImage!)
} else if user == "Basti" {
    LabelImage = UIImageView(image: TTV)
    LabelImage.addSubview(LabelImage!)
} else if user == "Matze" {
    LabelImage = UIImageView(image: TTT)
    self.view.addSubview(LabelImage!)
} else if user == "Steven" {
    LabelImage = UIImageView(image: TTR)
    self.view.addSubview(LabelImage!)
} else {
    LabelImage = UIImageView(image: TTM)
    self.view.addSubview(LabelImage!)
}

But then I get the following error in the line self.view.addSubview(LabelImage!):

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Unfortunately I can't find the mistake on my own.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • You are setting a new UIImageView to the var instead of setting its image property. Btw LabelImage it is probably already a subview of your view if you have already added it in you IB. Note that it is Swift convention to name your vars starting with a lowercase letter and there is no need to pass the file extension png for the images located in your Asset. `labelImage.image = UIImage(named: "TT_C")!` – Leo Dabus Dec 08 '17 at 03:42
  • Note that Swift is a type inferred language so there is no need to implicitly set the variable type to `UIImage`. `let ttc = UIImage(named: "TT_C.png")!` – Leo Dabus Dec 08 '17 at 03:46
  • I would recommend also instead of multiple if conditions just use a switch statement and provide all cases and a default one at the end – Leo Dabus Dec 08 '17 at 03:48
  • 1
    Okay that works! Thank you a lot. Yes I understand, what you said. But I started learning Swift just two weeks ago and I know, that there is still a loooooot to learn for me! Tanks again! – Sebastian W. Dec 08 '17 at 03:56

0 Answers0