2

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!

Uma Madhavi
  • 4,851
  • 5
  • 38
  • 73
StrawHat
  • 351
  • 1
  • 6
  • 14

3 Answers3

2
    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.

Soham Ray
  • 215
  • 2
  • 4
0

try this

button.setImage(image, for: .normal) // Swift 3
Muhammad Raza
  • 952
  • 7
  • 24
  • es but how do I acces the setImage?? can I create both a @IBOutlet weak var button: UIButton! and IBAction func chooseImage(_ sender: Any) { on the same button? – StrawHat May 06 '17 at 11:32
  • Thanks! I tried and it worked somewhat, now that I choose an image. it shows all blue... (the button image)?? it dosen't set the correct image – StrawHat May 06 '17 at 11:35
  • Check this solution, this will help. http://stackoverflow.com/questions/18133465/setting-uibutton-image-results-in-blue-button-in-ios-7 – Muhammad Raza May 06 '17 at 11:38
  • 1
    It worked by setbackgroundImage as Ray_soham told about.. Thanks for the help! – StrawHat May 06 '17 at 11:39
0

Use setImage() method to set the foreground image of a button. However, if your buttons are all blue, that's because there is a feature for images called "Rendering Mode" you should be aware of, please refer to Template Images for more information:

button.setImage(image.withRenderingMode(.alwaysOriginal), for: .normal)