Search code examples
iosswiftuiimageviewibaction

Swift: IBAction to put image in UIImageView after a button is clicked


I'm working in Swift and I'm trying to create a simple IBAction that puts an image (that I've already loaded in my assets) into a UIImageView once a button is clicked.

I've control-dragged and hooked everything up and yet I'm getting this error: "cannot convert expressions type '()' to type 'UIImage!'" I'm a beginner so please explain all answers thoroughly. My code:

@IBAction func colorBtnClicked(sender: UIButton) {
        colorsPanel.image = "Red_colors_panel"

        }

Solution

  • First of all you need to pass an UIImage to the .image property but there is a String object and this cause the error. To read image from your project bundle you need to do it the the following way:

    colorsPanel.image = UIImage(named: "Red_colors_panel.png") // and do not forget the extension