[英]Generating a random number under super.ViewDidLoad
I am making a 'Guess The Number' Game for a project at school, I want my application to generate one random number between 1-10 and then let me use it under my button which allows the user to guess the number by entering their guess into a text field. 我正在为学校的一个项目制作“猜数字”游戏,我希望我的应用程序在1-10之间生成一个随机数字,然后让我在按钮下使用该数字,该按钮允许用户通过输入猜测来猜测数字进入文本字段。 I have managed to do some of this, my random number generator is currently under my 'Guess' Button which means every time they press the button the number will change.
我已经设法做到了这一点,我的随机数生成器当前位于“猜测”按钮下,这意味着他们每次按下按钮时,数字都会改变。 My solution is to generate a number under super.viewDidLoad and then use it under the button to do the rest, but I'm not sure how to do this.
我的解决方案是在super.viewDidLoad下生成一个数字,然后在按钮下使用它来执行其余操作,但是我不确定如何执行此操作。
Use the standard library functions for high quality random numbers: arc4random()
or arc4random_uniform()
, just as in Objective-C. 将标准库函数用于高质量随机数:
arc4random()
或arc4random_uniform()
,就像在Objective-C中一样。
They are in the Darwin module, so you will need to import Darwin
if you haven't imported AppKit, UIKit, or Foundation. 它们在Darwin模块中,因此,如果您尚未导入AppKit,UIKit或Foundation,则需要
import Darwin
。
If I've understood you correctly you want the number to be generated only once instead of on every press. 如果我对您的理解正确,那么您希望该数字仅生成一次,而不是每按一次生成一次。
So you might want something like this: 因此,您可能需要这样的东西:
var randomNumber: Int
override func viewDidLoad() {
super.viewDidLoad()
//Initialization
generateRandomNumber()
}
func generateRandomNumber() {
randomNumber = Int(arc4random_uniform(9)) + 1
}
randomNumber is an instance-variable, so you can access it in all of your methods, for example to check if the user guessed correctly. randomNumber是一个实例变量,因此您可以使用所有方法访问它,例如,检查用户是否正确猜到了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.