因此,我为简单的iOS应用获得了此代码。当我按下touchPressed按钮时,该按钮应该在屏幕上获得一个新的随机位置,并且labelScore应该使用按钮触摸的次数进行更新。我的一个 friend 在Objective-C中尝试了此方法,并且有效。

问题是:我在touchedPressed中有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)在按钮的IBOutlet中添加一个ViewController:
@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
    }
}

09-11 10:11