所以我为我的简单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.
}
}
答案 0 :(得分:3)
现在@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
}
}
答案 1 :(得分:2)
这是因为绘图/布局系统的工作方式。你有一个小的计时问题,这就是全部。真正发生的事情是按钮正在移动,但是之后立即进行布局并再次将其放回原位。一种解决方案是在短时间内将除newScore
之外的所有内容包装起来,如下所示:
@IBAction func touchPressed(button: UIButton) {
delay(0) {
// Find the button's width and height
var buttonWidth = button.frame.width
// ...
}
self.newScore()
}
或者,在此storyboard / xib文件中关闭“自动布局”。这也解决了这个问题(尽管出于其他原因这可能是不可接受的)。