所以我得到了我的简单iOS应用程序的代码。当我按下touchPressed按钮时,按钮应该在屏幕上获得一个新的随机位置,并且标签Score应该用按钮触摸的数量更新自身。我的一个朋友在Objective-C中尝试了这一点,它的工作原理。奇怪的@IBAction冲突或错误? (Swift)
问题是:我有touchPressed中的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 2014-09-27 17:42:47
也许有人找到了解决方法.. – perte 2014-09-27 17:45:38