Reputation: 3
in my app I have a Next button and a Solution button. When you press next a new card comes up (i.e. Image card1), if you press again next another card comes up in a random way. My question is how to display the solution for each card selectively (i.e. for card1 there is the sol1)
@IBAction func nextbutton(sender: AnyObject) {
//Randomize a number for the first imageview
var firstRandomNumber = arc4random_uniform(2) + 1
//Construct a string with the random number
var firstCardString:String = String(format: "card%i", firstRandomNumber)
// Set the first card image view to the asset corresponding to the randomized number
self.Image1.image = UIImage(named: firstCardString)
}
@IBAction func solutionbutton(sender: AnyObject) {
}
Upvotes: 0
Views: 68
Reputation: 4360
I have attached a complete sample of your problem.The problem with your code was that variables you were creating in the next button are of limited scope and we want the same random no value for the solution card.Now they are beyond the scope of next action and easily accessible in this class just by using the keyword self
import UIKit
class YourViewController : UIViewController {
var randomNumber:Int = 0
var cardString:String = ""
var solutionString:String = ""
@IBAction func nextbutton(sender: AnyObject) {
//Randomize a number for the first imageview
self.randomNumber = arc4random_uniform(2) + 1
//Construct a string with the random number
self.cardString = String(format: "card%i", self.randomNumber)
self.solutionString = String(format: "sol%i", self.randomNumber)
// Set the first card image view to the asset corresponding to the randomized number
self.Image1.image = UIImage(named: self.cardString)
}
@IBAction func solutionbutton(sender: AnyObject) {
self.Image1.image = UIImage(named: self.solutionString)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Upvotes: 0