如何让按钮执行首个true的if语句后停止,直至下次点击?
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") } }
2. Use an Index Counter (Recommended for Scalability)
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

