奇怪的@IBAction冲突或错误? (迅速)

所以我为我的简单iOS应用程序获取了此代码。 当我按下touchPressed按钮时,按钮应该在屏幕上获得一个新的随机位置,labelScore应该自动更新按钮触摸次数。 我的一个朋友在Objective-C中试过这个并且它有效。

问题是:我在triggeredPressed中有newScore(),而按钮没有获得新位置。 如果我评论newScore(),则随机位置操作有效。

提前致谢。

// ViewController.swift import UIKit import SpriteKit class ViewController: UIViewController { @IBOutlet var backgroundImage: UIImageView! @IBOutlet var scoreLabel: UILabel! 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. } // Initial score var score:Int = 0 // Update the actual score with the one matching th number of touches func newScore() { score = score + 1 scoreLabel.text = "SCORE: \(score)" } // Get the random height for the button (with limits) func randomButtonHeight(min: Float, max:Float) -> Float { return min + Float(arc4random_uniform(UInt32((max-90) - min + 1))) } @IBAction func touchPressed(button: UIButton) { // Find the button's width and height var buttonWidth = button.frame.width var buttonHeight = button.frame.height // Find the width and height of the enclosing view var viewWidth = button.superview!.bounds.width var viewHeight = button.superview!.bounds.height // Compute width and height of the area to contain the button's center var xwidth = viewWidth - buttonWidth var yheight = viewHeight - buttonHeight // Generate a random x and y offset var xoffset = CGFloat(arc4random_uniform(UInt32(xwidth))) var yoffset = CGFloat(self.randomButtonHeight(100, max: Float(viewHeight))) // Offset the button's center by the random offsets. button.center.x = xoffset + buttonWidth / 2 button.center.y = yoffset + buttonHeight / 2 newScore() // this works but the action above this doesn't and if I comment this line, the action above works. } } 

现在@matt已经确定了问题,我还有另外一个关于如何处理它的建议:

1)向ViewController添加两个新变量:

 var newButtonX: CGFloat? var newButtonY: CGFloat? 

2)更新按钮的位置时,将它们设置为touchPressed()

 // Offset the button's center by the random offsets. newButtonX = xoffset + buttonWidth / 2 newButtonY = yoffset + buttonHeight / 2 button.center.x = newButtonX! button.center.y = newButtonY! 

3)为ViewController添加按钮的IBOutlet

 @IBOutlet weak var button: UIButton! 

并在Interface Builder中连接它。

4)然后覆盖viewDidLayoutSubviews如下所示:

 override func viewDidLayoutSubviews() { if let buttonX = newButtonX { button.center.x = buttonX } if let buttonY = newButtonY { button.center.y = buttonY } } 

这是因为绘图/布局系统的工作方式。 你有一个小的计时问题,就是这样。 真正发生的事情是按钮正在移动,但是之后立即进行布局并再次将其放回原位。 一种解决方案是在短时间内将除调用newScore之外的所有内容包装起来,如下所示:

 @IBAction func touchPressed(button: UIButton) { delay(0) { // Find the button's width and height var buttonWidth = button.frame.width // ... } self.newScore() } 

或者,在此storyboard / xib文件中关闭“自动布局”。 这也解决了这个问题(尽管出于其他原因这可能是不可接受的)。