基于派生的CGRect名称设置UIButton框架是否返回CGRectZero?

时间:2018-03-13 01:48:39

标签: swift uibutton concatenation cgrect

请查看下面的代码,了解我想要实现的目标,我将非常感谢有关如何实现这一目标的建议。我正在使用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: - 互动

@IBAction func TEMP1(_ sender: Any) {

    playBubble.frame = CGRectFromString("bubble\(playBubblePosition)")
    self.view.layoutIfNeeded()

    playBubblePosition += 1

    if playBubblePosition == 5 {
        playBubblePosition = 1
    }
}

如果我设置:

  playBubble.frame = bubble1

它正常工作。但是,当尝试换出bubble1,bubble2,bubble3和bubble4中的数字时(因为它是唯一改变的东西),它将我的playBubble(UIButton)设置为CGPoint(0,0)。

可能导致这种情况发生的原因是什么?我知道它可能“格式错误”,但是在我的CGRect中交换这个数字的正确方法是什么?

非常感谢!

1 个答案:

答案 0 :(得分:1)

CGRectFromString期待一个类似"{{10,20},{35,47}}"的字符串,它可以解析并变成CGRect。它不能用于从顺序命名的变量中选择值。您可以使用数组来执行此操作。

将您的气泡放入数组文字并使用playBubblePosition - 1作为索引来选择所需的气泡:

playBubble.frame = [bubble1, bubble2, bubble3, bubble4][playBubblePosition - 1]