Reputation: 940
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.
Upvotes: 4
Views: 12326
Reputation: 12910
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
}
Upvotes: 0
Reputation: 3538
The error should be related to the way you push or present the ViewController
. Seems the outlet is not created yet when you show or present it. Should use instantiateViewControllerWithIdentifier
as below example
let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("YourStoryBoardId")
self.navigationController?.pushViewController(viewController!, animated: true)
Upvotes: 0
Reputation: 151
Easy way : Drag and drop that image to your file view/project navigator on Xcode.
Select the image view - Then attribute inspect - Under image - Select the file name of the image you wish to load.
Enjoy the drags and drops whenever you can.
Hardway:
if let filePath = Bundle.main.path(forResource: "imageName", ofType: "jpg"), let image = UIImage(contentsOfFile: filePath) { imageView.contentMode = .scaleAspectFit
imageView.image = image
}
Upvotes: 2