Please review my code below to get the gist of what I am trying to achieve, and I would greatly appreciate suggestions on how to achieve it. I am using Swift:
var playBubblePosition = 1
var bubble1 = CGRect(x: 0, y: 0, width: 0, height: 0)
var bubble2 = CGRect(x: 0, y: 0, width: 0, height: 0)
var bubble3 = CGRect(x: 0, y: 0, width: 0, height: 0)
var bubble4 = CGRect(x: 0, y: 0, width: 0, height: 0)
override func viewDidLoad() {
super.viewDidLoad()
//This isn't necessary to share (too long), but in my viewDidLoad
//method, I am setting the values of bubble1, bubble2, bubble3 and
//bubble4 based on screen size. It prints to the log correctly.
}
//Do any initial animations once the view appears to the user. ------------------------------------
override func viewDidAppear(_ animated: Bool) {
playBubble.frame = bubble1 //playBubble is a UIButton
}
//MARK: - Interactions
@IBAction func TEMP1(_ sender: Any) {
playBubble.frame = CGRectFromString("bubble\(playBubblePosition)")
self.view.layoutIfNeeded()
playBubblePosition += 1
if playBubblePosition == 5 {
playBubblePosition = 1
}
}
If I set:
playBubble.frame = bubble1
It works correctly. However, when trying to swap out the number in bubble1, bubble2, bubble3 and bubble4 (as it is the only thing changing) it sets my playBubble (UIButton) at CGPoint(0,0).
What could be causing this to happen? I know it may be 'badly formatted', but what would be the correct way to swap out this number in my CGRect?
Many thanks!
CGRectFromString
is expecting a string like "{{10,20},{35,47}}"
which it can parse and turn into a CGRect
. It can't be used to select a value from sequentially named variables. You can use an array to do that.
Put your bubble rects into an array literal and use playBubblePosition - 1
as the index to select the desired one:
playBubble.frame = [bubble1, bubble2, bubble3, bubble4][playBubblePosition - 1]