问题
When I insert an Image to my View like this it works:
func loadSomeImage() {
var imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150))
var image = UIImage(named: "myImage.jpg")
imageView.image = image
self.view.addSubview(imageView)
}
My problem with this code is, that the ImageView is not shown in the Interface Builder.
When I write this code however, I get an error:
@IBOutlet weak var imageView: UIImageView
func loadSomeImage() {
self.imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150))
var image = UIImage(named: "myImage.jpg")
imageView.image = image
self.view.addSubview(imageView)
}
fatal error: unexpectedly found nil while unwrapping an Optional value
Why is that? Can I insert an Image which is shown in the Interface Builder but has my own code implementation to change some features the Attribute Inspector can't change?
Thanks for your help!
回答1:
The problem with your code is that there are two different instances of UIImageView. One you are creating via interface builder and another one you are creating via code.
self.imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150))
This creates another instance of UIImageView and hence it is different from the imageView you have placed on interface builder. Simply remove this line of code and it will work. Also there is no need to addSubview again if you are using XIB.
Refine your code to this:
@IBOutlet weak var imageView: UIImageView
func loadSomeImage() {
var image = UIImage(named: "myImage.jpg")
self.imageView.image = image
}
This should be enough.
来源:https://stackoverflow.com/questions/25140469/uiimageview-with-iboutlet-in-swift-to-see-it-in-the-interface-builder