简体   繁体   中英

Ios - change image of UIImageView when pressing a UIButton

So I am developing my first app in iOS and I don't know how to fix this. In the same view I have: - two buttons inside a stackView (that I modified) - an UIImageView Storyboard View

Depending on which button I press, I want the image to change in UIImageView . However, bc the buttons are in the stackView , I can't push an IBAction from them to the controller.

I changed the image based on the button inside the function didViewLoad() , but as I learned, that function is only called once, so when when I press the buttons in the app it has no more effect in the UIImageView .

This is my controller for this view Controller Code

And this is the beginning of the code for the subclass of the UIStackView UIStackView subclass

In your case, you also have the option of using Segmented Controller.

Place the segmented controller in your View Controller in the StoryBoard.

Make an outlet of the Segment Controller

@IBOutlet var segmentedController: UISegmentedControl!

Make an IBAction Function for Value Changed event in the Segmented Control. Now whenever the selected tabs are changed you will be notified.

@IBAction func SegmentTapped(_ sender: Any) {
    switch segmentedController.selectedSegmentIndex {
    case 0:
        // Change Image Here
    case 1:
        // Change other image here
    default:
        // Statement to execute if no other case is present
    }
}

Using Segmented Controller would be a good idea for this case. Thank you for that.

For the more general approach of how to make things happen with what I had already written, this post ( Open a storyboard view with a stackview button in Swift 3 and Xcode ) was very useful and also taught me how to properly use protocols and delegates.

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