Jamil Jamil - 2 months ago 19
Swift Question

How to add image to UIImageView?

I'm trying to add image to

UIImageView
, but after I do it
UIImageView
is nil. Here's my code:

class ViewController: UIViewController {

@IBOutlet var myView: UIView!
@IBOutlet weak var testImg: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
UIGraphicsBeginImageContext(CGSize(width: 500,height: 500))
var path = UIBezierPath()
path.lineWidth = 1.0
path.moveToPoint(CGPoint(x: 150, y: 150))
var x = 151
for ;x<300;x++
{
path.addLineToPoint(CGPoint(x: x, y: x))
path.moveToPoint(CGPoint(x: x, y: x))
}
path.stroke()
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
testImg = UIImageView(image: img)
testImg.frame = CGRect(x: 0,y: 0,width: 500,height: 500)
myView.addSubview(testImg)
// 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.
}
}


When I try to set frame for
UIImageView
, I got this error:


fatal error: unexpectedly found nil while unwrapping an Optional value


Probably, i don't create image correctly.

UPDATE

testImg = UIImageView(image: img)


This line of code overwrites
IBOutlet
of
UIImageView
, removing it and doing simply
testImg.image = img

fixed problem.

Answer

Simply:

if let image = img {
    // you don't have to instantiate an imageView again, IBOutlet handles it for you    
    testImg.image = image
    print("Works")
    // if you don't see this output in your debug console, the condition never succeeds and an img is really nil
}