简体   繁体   中英

Set ImageView to current image of UIButton on tap in Swift

In building an app I'm trying do as it says in the title, I want to change an Imageview to the image currently set in a UIButton by tapping that button.

I know how to do this:

@IBAction func play1(_ sender: AnyObject){
    Activepic1.image = UIImage(named: "Blank Image")
}

Right now it sets the Activepic1 to a "Blank Image" that I have in my asset library. I did that to test the app as is.. but what I want to happen is for it to assign whatever image is currently displayed as the UIButton.

Is there a function I can use to put the Current Image of the button rather than using the (named: "asset") function?

Thanks in advance

The easiest way would be to create an outlet (and hook it up) for your button as well as your action and just access the button's image from it.

Using swift 3

@IBOutlet weak var imageBttn: UIButton!
....

@IBAction func play1(_ sender: Any){
    Activepic1.image = imageBttn.currentImage!
}

Alternative way without having to create a new outlet

@IBAction func play1(_ sender: Any){
    Activepic1.image = sender.currentImage!
}

The first solution can utilise any button hooked up to the imageBttn outlet while the second strictly uses the button that is connected to the action itself.

Here is the Code which worked for me I used storyBoard

1) Connect the UIButton and ImageView to the ViewController.swift file

  @IBOutlet var myImageView: UIImageView!
  @IBOutlet var myButton: UIButton!

2) Define the action of the Action of the UIButton as:

@IBAction func myButtonTapped(sender: AnyObject) {
 myImageView.image = myButton.imageView!.image 
}

Before tapping Button

在此输入图像描述

After tapping Button

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM