How to set an image in imageview swift 3?
Asked Answered
H

5

15

So I have an image view titled cashOrCredit and have am trying to set it's image programatically but somehow not able to.

First I set the image like this

cell.cashOrCredit.image = UIImage(named: "cash1.png")

and I get an error saying a separator of "," is needed.

Then I tried it this way

var cashImage: UIImage?
cashImage = "cash1.png"
cell.cashOrCredit.image = cashImage

But I get a THREAD 1 EXC BAD INSTRUCTION error. I can't seem to understand what is going wrong ?

Here is the error

1

Heaume answered 22/8, 2017 at 8:23 Comment(1)
If cashOrCredit is an IBOutlet you should verify that it is correctly connected in Interface Builder.Peevish
B
16

Updated for Swift 3:

use below simple code, to set the image to UIImageView;

class YourViewControllerName: UIViewController {

        var mYourImageViewOutlet: UIImageView?

        func addImageToUIImageView{
            var yourImage: UIImage = UIImage(named: "Birthday_logo")!
            mYourImageViewOutlet.image = yourImage
        } // call this function where you want to set image.
     }

Note: "Birthday_logo" type of image must be present in your Assets.xcassets of your project. I attached the screenshot if you want any help please refer it.

****// used anywhere you want to add an image to UIImageView. [Here I used one function & in that function, I write a code to set image to UIImageView]****

Enjoy..!enter image description here

Bursiform answered 25/11, 2017 at 7:2 Comment(0)
O
11

Try this:

cell.cashOrCredit.image = UIImage(named: "cash1")

and check "cash1.png" image is available in Assets.xcassets or not.

If you get solution, then give upvote to my answer.

Octavo answered 22/8, 2017 at 9:40 Comment(0)
B
2

Delete ".png":

cell.cashOrCredit.image = UIImage(named: "cash1")

You can also set it all programmatically:

let cellImage = UIImageView(frame: CGRect(x: X, y: Y, width: WIDTH, height: HEIGHT))
cellImage.image = UIImage(named: "cash1")
cell.addSubview(cellImage)
Ballard answered 23/8, 2017 at 8:50 Comment(0)
L
2

Take Outlet of ImageView

@IBOutlet weak var imgProfile: UIImageView!

Go through the following code which contains will be helpful you to pick image or capture image from the camera.

func choosePicker() {
        let alertController = UIAlertController(title: "Select Option", message: nil, preferredStyle: (IS_IPAD ? UIAlertControllerStyle.alert : UIAlertControllerStyle.actionSheet))
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { action -> Void in
        })
        let gallery = UIAlertAction(title: "From Gallery", style: UIAlertActionStyle.default
            , handler: { action -> Void in
                self.openPicker(isCamera: false)
        })
        let camera = UIAlertAction(title: "Take Photo", style: UIAlertActionStyle.default
            , handler: { action -> Void in
                self.openPicker(isCamera: true)
        })
        alertController.addAction(gallery)
        alertController.addAction(camera)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }

func openPicker(isCamera : Bool) {
        let picker:UIImagePickerController?=UIImagePickerController()
        if isCamera {
            picker!.sourceType = UIImagePickerControllerSourceType.camera
        } else {
            picker!.sourceType = UIImagePickerControllerSourceType.photoLibrary
            picker!.allowsEditing = true
        }
        picker?.delegate = self

        if UIDevice.current.userInterfaceIdiom == .phone {
            self.present(picker!, animated: true, completion: nil)
        }
        else {
            picker!.modalPresentationStyle = .popover
            present(picker!, animated: true, completion: nil)//4
            picker!.popoverPresentationController?.sourceView = imgProfile
            picker!.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.up
        }
    }

// MARK: - UIImagePickerControllerDelegate Methods
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            self.imgProfile.image = image
        }
        picker.dismiss(animated: true, completion: nil);
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }

Call choosePicker method wherever you want to call.

Lysenkoism answered 26/10, 2018 at 7:8 Comment(0)
B
1

Check if cashOrCredit is uiimageview.

Secondly,

cashImage = UIImage(named: "cash1.png")

If that doesnot work, try

cell?. cashOrCredit.image

check if cell is nil?

In the context of Swift code, EXC_BAD_INSTRUCTION usually means you’ve hit a compiler trap, that is, an undefined instruction inserted into the code by the compiler because of a bug detected at runtime. The most common cause of these are:

  1. failure to unwrap an optional — This can be a forced unwrap (!) or an implicit unwrap (accessing an implicitly unwrapped optional that’s nil).

  2. array out of bounds

  3. a failed forced cast (as!), either because the value was a nil optional or because the value was of the wrong type

Baylor answered 22/8, 2017 at 9:11 Comment(10)
@IBOutlet weak var cashOrCredit: UIImageView! This is how the cashOrCredit is definedHeaume
@A.G did you put the image in assets folder as an image set?? Or just drag to your project??Baylor
Even if you misspelled the image name, its not going to crash your program. I think the error is somewhere else. Can you post the debug error??Baylor
I tried both ways but it still gives me the same errorHeaume
@A.G could u show me the error in the debug??. Pic or something??Baylor
I can't show you a picture because I can't put it on a stack overflow comment.Heaume
Edit your question with pic. Can yiu tell the error code after BAD INSTRUCTION.??Baylor
I have added itHeaume
@A.G hey, try ? After cell. cell?.cashOrCredit.imageBaylor
@A.G i think the cell is nil.Baylor

© 2022 - 2024 — McMap. All rights reserved.