-1

This is my code:

override func viewDidLoad() {
    super.viewDidLoad()

    var label89val: LTMorphingLabel!
    label89val = LTMorphingLabel(frame: CGRectMake(20, 10, 80, 80))
    label89val.delegate = self
    label89val.morphingEffect = .Scale
    label89val.text = "0"
    label89val.textColor = UIColor.whiteColor()
    label89val.font = UIFont.boldSystemFontOfSize(23)
    label89val.setNeedsDisplay()
    self.view.addSubview(label89val)

It crashes at:

label89val.text = "0"

and shows this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

Moon Cat
  • 2,029
  • 3
  • 20
  • 25
Jason Zhao
  • 1,278
  • 4
  • 19
  • 36

3 Answers3

-1

I had the same thing here and for me the solution was as follows.

Every now and than I put my own variables and expressions into the debugging area to see right away if their values are correct. Some of those expressions had "unvalid expression" as result. Removing all of these "unvalid expression" solved the problem. The error doesn´t come up anymore.

Hope this helps

Ronald Hofmann
  • 1,390
  • 2
  • 15
  • 26
-1

Try this:

override func viewDidLoad() {
    super.viewDidLoad()


    if let label89val = LTMorphingLabel(frame: CGRectMake(20, 10, 80, 80)) {
       label89val.delegate = self
       label89val.morphingEffect = .Scale
       label89val.text = "0"
       label89val.textColor = UIColor.whiteColor()
       label89val.font = UIFont.boldSystemFontOfSize(23)
       label89val.setNeedsDisplay()
       self.view.addSubview(label89val?)
    }
}
D4ttatraya
  • 3,344
  • 1
  • 28
  • 50
-1

You're force unwrapping that label at the first and it should crash while setting it's frame. So, just try to make the code look like this and it properly works.

override func viewDidLoad() {
    super.viewDidLoad()
        let lblName = LTMorphingLabel()
        lblName.frame = CGRect(x: 20, y: 10, width: 180, height: 80)
        lblName.delegate = self
        lblName.morphingEffect = .scale
        lblName.text = "Swift Trial"
        lblName.textColor = .gray
        lblName.font = UIFont.boldSystemFont(ofSize: 23)
        lblName.setNeedsDisplay()
        self.view.addSubview(lblName)
    }
  • Sorry but this answer is wrong. The OP is not force unwrapping anything. The line `var label89val: LTMorphingLabel!` is declaring an implicitly unwrapped variable. Also note that the OP states the crash happens on the line `label89val.text = "0"`. At that point the `label89val` variables has already been accessed several times. – HangarRash Apr 24 '23 at 17:12