Search code examples
iosswiftimagebuttonuiimagepickercontroller

How I get the image of a button in swift?


I set an image to a button using this code

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {


    let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage


        btnImg1.contentMode = .scaleAspectFit
        btnImg1.setImage(chosenImage, for: UIControlState.normal)

dismiss(animated: true, completion: nil)
}

now how I can get the selected image or I mean how to get the image of the button? I want the image to save it somewhare.. please help , thanks in advance


Solution

  • UIButton contain ImageView, and when you assign image to UIImageView you can get is with its .image property

    So for UIButton get ImageView and then Image

    button.imageView?.image would give the image assigned to UIButton If your button have different image for state you can also use .

        button.image(for: .normal or what ever state)
        button.imageView?.image   
    

    (Both will give same result if you set image with .normal)

    enter image description here

    @Rooh Al-mahaba You can access all property of UIImageView if you have UIButton object as UIButton contain an UIImageView to handle Image related part