简体   繁体   中英

Show or hide items by clicking button

I have four imageview contents in an XIB and a button that covers all my XIB. I want to make when the user tap the button, the first imageview is shown, the next tap is hidden and the second imageview is displayed and so on until all my imageview is shown / hidden. What would be the most efficient way to do it?

Save all your UIImageViews to an array , and current showing imageView to a variable, it may look like this:

var imageViews: [UIImageView] = []

var currentImageViewIndex = 0 {
    didSet {
        if currentImageViewIndex >= imageViews.count { currentImageViewIndex = 0 }
        imageViews[oldValue].isHidden = true
        imageViews[currentImageViewIndex].isHidden = false
    }
}

func handleTap() {
    currentImageViewIndex += 1
}

I suggest you use a state variable that contains an enum listing the various states (firstImageVisible, secondImage.... ) then you can have a function inside the enum that switches to the nextState (being the target of your button action) you can also easily iterate through states of an enum, check the documentation for the CaseIterable protocol. Often having a property observer (didSet) on the state is a handy place to update other parts of the UI which need to change every time the state changes.

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