2

I am trying to apply slide, fade and grow effect to my imageview. Following is my code

@IBAction func fadeIn(_ sender: Any) {
    imageView.alpha=0
    UIView.animate(withDuration: 1, animations: {
        self.imageView.alpha=1
    })
}

@IBAction func slideIn(_ sender: Any) {
    imageView.center=CGPoint(x:imageView.center.x-500,y:imageView.center.y)
    UIView.animate(withDuration: 2) {
        self.imageView.center=CGPoint(x:self.imageView.center.x+500,y:self.imageView.center.y)
    }

}

@IBAction func grow(_ sender: Any) {
    imageView.frame=CGRect(x:0,y:0,width:0,height:0)
    UIView.animate(withDuration: 1, animations: {
        self.imageView.frame=CGRect(x:0,y:0,width:200,height:200)
    })
}

Whenever i click on any of the button i get

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

Any help would be greatly appreciated.

pkamb
  • 33,281
  • 23
  • 160
  • 191
Lata Sawant
  • 49
  • 1
  • 8
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Tamás Sengel Dec 13 '17 at 15:03
  • show your `imageView` declaration code. Is it IBOutlet? – Krunal Dec 13 '17 at 15:05

2 Answers2

2

(You have provided incomplete information in your question, so can't say exact root of issue. I can suggest this, according to information in question)

Your imageView should/may be an IBOutlet variable/property and you may not have connected it with your storyboard/XIB view controller interface element.

Solution:
Connect (or reconnect) your imageView with your interface element.

enter image description here

Krunal
  • 77,632
  • 48
  • 245
  • 261
0
Hope all functions are correct for animation. You should first get unwrapped value then try to do further operation. It will result to avoid crash

IBAction func fadeIn(_ sender: Any) {
        if let img = imageView {
            img.alpha=0
            UIView.animate(withDuration: 1, animations: {
                self.img.alpha=1
            })
        }
    }

    @IBAction func slideIn(_ sender: Any) {
        if let img = imageView {
            img.center=CGPoint(x:img.center.x-500,y:img.center.y)
            UIView.animate(withDuration: 2) {
                self.img.center=CGPoint(x:self.img.center.x+500,y:self.img.center.y)
            }
        }

    }

    @IBAction func grow(_ sender: Any) {
        if let img = imageView {
            img.frame=CGRect(x:0,y:0,width:0,height:0)
            UIView.animate(withDuration: 1, animations: {
                self.img.frame=CGRect(x:0,y:0,width:200,height:200)
            })
        }
    }
Jeetendra Kumar
  • 500
  • 3
  • 9