Search code examples
iosswiftbuttonuiimagepickercontroller

How to set image on button


I'm new to swift and I've searched different places and couldn't really find anything helpful.

I am in this case that I pick an image from UIImagePickerController when pressing on the button:

@IBAction func chooseImage(_ sender: Any){}

which works and I can access the photo library and choose an image but.. the thing is that I want to set it to the button image. I save the image to:

func imagePickerController(_ picker: UIImagePickerController,   didFinishPickingMediaWithInfo info: [String : Any])
{
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage

    // this works with an UIimageView.image but I can't get it to work with the button

    ???.image = image

I believe the way to do it is to say; button.ImageView.image = image and this can only be done by creating a variable called UIButton!?? and then I can set

button.ImageView.image = image

otherwise I can't enter the method ImageView.image

But the thing is that chooseImage is the same button I use for the action of receiving the image... So can I both make a @IBOutlet weak var button: UIButton! and @IBAction on the same button?? Well I tried and created both a

@IBOutlet weak var button: UIButton!

and

@IBAction func chooseImage(_ sender: Any) {

button.imageView.image = image
}

but nothing happened It might sound confusing,but there is two questions. Is it possible to do it this way? and if yes, why isn't the picture being shown when doing

 button.imageView.image = image?

and if not please tell me what im doing wrong :-)

Thanks!


Solution

  •     someButton.setImage(imagenew, for: .normal)
    

    There is a setimage method for UIButton. you can also set image as background image. There is a method called setbackgroundImage.