【发布时间】:2014-11-22 12:11:16
【问题描述】:
所以我得到了我的简单 iOS 应用程序的代码。当我按下 touchPressed 按钮时,该按钮应该在屏幕上获得一个新的随机位置,并且 labelScore 应该使用按钮触摸次数自行更新。我的一个朋友在 Objective-C 中尝试过这个,它可以工作。
问题是:我在 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.
}
}
【问题讨论】:
-
问得很好——我可以很容易地重现这个问题。
-
也许有人找到了解决方法..
标签: ios xcode swift uikit xcode6