You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让按钮执行首个true的if语句后停止,直至下次点击?

Fixing Sequential Image Switching on Button Tap

Hey there! The issue you're hitting is that each independent if statement runs one after another in a single button tap. As soon as you update the image in the first matching condition, the next if checks that new image and triggers immediately—so you jump straight to the last image in one go. Here are two straightforward fixes:

1. Use else if Instead of Multiple if Statements

This is the simplest quick fix. By chaining conditions with else if, once one condition is met and executed, all subsequent checks are skipped.

@IBAction func addone(_ sender: UIButton) {
    if onesimage.image == UIImage(named: "ones0") {
        onesimage.image = UIImage(named: "ones1")
    } else if onesimage.image == UIImage(named: "ones1") {
        onesimage.image = UIImage(named: "ones2")
    } else if onesimage.image == UIImage(named: "ones2") {
        onesimage.image = UIImage(named: "ones3")
    } else if onesimage.image == UIImage(named: "ones3") {
        onesimage.image = UIImage(named: "ones4")
    } else if onesimage.image == UIImage(named: "ones4") {
        // Optional: Loop back to the first image when reaching the end
        onesimage.image = UIImage(named: "ones0")
    }
}

Comparing UIImage objects directly can sometimes cause unexpected issues (e.g., UIImage(named:) might return different instances for the same asset). A better approach is to track the current image with an index, which is also easier to maintain if you add more images later.

First, add these properties to your view controller class:

// Track the current image position
private var currentImageIndex = 0
// List all your image names in order
private let imageNames = ["ones0", "ones1", "ones2", "ones3", "ones4"]

Then update your button action:

@IBAction func addone(_ sender: UIButton) {
    // Increment the index, loop back to 0 when we hit the last image
    currentImageIndex = (currentImageIndex + 1) % imageNames.count
    // Set the image using the updated index
    onesimage.image = UIImage(named: imageNames[currentImageIndex])
}

This method keeps your code clean, avoids messy condition chains, and makes it trivial to add or remove images later—just update the imageNames array!

内容的提问来源于stack exchange,提问作者Nick Senior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:22:29