所以我得到了我的简单 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.
}
}
现在@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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)