简体   繁体   中英

Swift UIImage as button

I'm now learning to make an audio recorder app. Basically, I want to add a tap gesture to a UIView to trigger/stop the recording. After triggering my recorder, the image should be changed to another one. My question is:

Am I supposed to control drag two @IBAction functions or only one? How to distinguish the "trigger" and "stop" action? My guess is I may only need one function, and at the beginning of it, I check the image name: if it's the recording icon or the stop icon, and do something accordingly. However, I cannot find the property of UIImage to identify the image it contains.

I'm new to ios so this may not be a good question, but please bear with me. By the way, I'm doing this using interface builder.

You only need one IBAction for the same and you can check for the image through following code inside the action:

if yourImageView.image == UIImage(named: "yourImageName") {
//perform some action here
} else {
//perform some action here 
}

You do this by using highlightedImage and isHighlighted properties of UIImageView . And you can do this by using single IBAction

In the viewDidLoad method :

yourImageView.image = UIImage(name:"RecordImage/TriggerImage")
yourImageView.highlightedImage = UIImage(name:"StopImage")

You can set these images in the interface builder too. As you can see in the following image you need set images for both Image and Highlighted properties.

UIImageView界面构建器

Inside your action method:

yourImageView.isHighlighted = !yourImageView.isHighlighted

if yourImageView.isHighlighted
{
  //so now the UIImageView shows stop image that means we are in recording mode
  // do the actions that are to be done in recording mode like start recording updating other UI etc 
}
else
{
 //so now the UIImageView shows Record/Trigger image that means are in normal mode or not recording
  // do the actions that are to be done in normal mode like stop recording (if required )updating other UI etc 
}

Step1 - declare a property in ViewController class to check the status of button

if is checked = true //recording is going on

if false //recording is stopped

//declaration in ViewController class
    var isChecked = false

Step 2 - add a button imageView and Assign its button action as below

 @IBAction func BottomImageBtnAction(_ sender: UIButton) {
        isChecked = !isChecked
        if isChecked {
            //here şet image as stop
        }
        else {
            //here set image as Start
        }
    }

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