Reputation: 35
I am developing a game for iOS 13 using Xcode 11 and Swift 5. (I'm a beginner.) I have 16 buttons on the screen, and I want to change a button's image and isEnabled setting randomly. I have this function that is called:
func startSequence()
{
timeUntilChange = Int.random(in: 1...2)
nextMole = Int.random(in: 0...15)
timeMoleShows = Double.random(in: 0.5...1.5)
timer = Timer.scheduledTimer(timeInterval: TimeInterval(timeUntilChange), target: self, selector: #selector(showMole), userInfo: nil, repeats: false)
}`
Then I have this:
@objc func showMole()
{
if gameInSession == true
{
moleImage_0.setBackgroundImage(UIImage(named:"mole_t.png"), for: [])
moleImage_0.isEnabled = true
}
}
So where I have moleImage_0
I want the 0
to be the randomly generated number held in the variable "nextMole".
I did search here and found some things about arrays and dictionaries. I tried an array, but couldn't figure it out.
Is what I'm trying to do possible?
Upvotes: 0
Views: 62
Reputation: 201
attach all buttons to outlet collections and update your showMole with following.
@IBOutlet var allButtons: [UIButton]!
@objc func showMole()
{
if gameInSession == true
{
allButtons[nextMole].setBackgroundImage(UIImage(named:"mole_t.png"), for: [])
allButtons[nextMole].isEnabled = true
}
}
Upvotes: 1
Reputation: 41
I like the answer mwahlig provided, but in case you are not sure how to get the 16 buttons into the moleButtons array, you'll need to add each one to it like this somewhere in your setup code:
moleButtons.append(button1)
moleButtons.append(button2)
moleButtons.append(button3)
// etc. for buttons 4 through 16
Also, as to your specific question about being able to randomly generate the "0" part of the variable name "moleImage_0" - you can't do that in Swift; constant and variable names are fixed when you declare and/or define them.
Hope that helps you out!
Upvotes: 0
Reputation: 176
To expand on what John said, you could store all your mole buttons in an array defined like so (assuming your buttons are instances/subclasses of UIButton
):
var moleButtons = [UIButton]()
Then you could even make your nextMole
value a computed property like so:
var nextMoleIndex: Int {
return Int.random(in: 0 ..< moleButtons.count)
}
Finally, your showMole
function can be updated to reference this array when updating the random button:
@objc func showMole() {
if gameInSession {
moleButtons[nextMoleIndex].setBackgroundImage(UIImage(named:"mole_t.png"), for: .normal)
moleButtons[nextMoleIndex].isEnabled = true
}
}
Hope this helps!
Upvotes: 1