UIImageView with IBOutlet in Swift to see it in the Interface Builder

拥有回忆 提交于 2020-01-14 06:02:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!