根据派生的 CGRect 名称设置 UIButton 帧是否返回 CGRectZero?



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

//标记: - 交互

@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中交换这个数字的正确方法是什么?

非常感谢!

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

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

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

最新更新