gpt4 book ai didi

ios - 奇怪的@IBAction 冲突或错误? ( swift )

转载 作者:搜寻专家 更新时间:2023-10-31 22:16:49 27 4
gpt4 key购买 nike

所以我为我的简单 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
}
}

关于ios - 奇怪的@IBAction 冲突或错误? ( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26077229/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com