【问题标题】:How Can I send the Random Value through a Button?如何通过按钮发送随机值?
【发布时间】:2013-10-11 15:28:46
【问题描述】:

我目前正在编写一个程序,它生成一个介于 1 和 100 之间的 answer 值:

int answer = 0;
answer = arc4random() % 100 + 1;

我首先让用户猜测屏幕上某个字段中的值。然后脚本将运行一个简单的循环来确定他们输入的值是否与随机的answer 值匹配。

此时,我有一个要求用户猜测的初始屏幕。他们输入一个数字并单击一个按钮以提交该值。问题是,如果他们没有从第一个条目中猜出 answer 值,那么答案值会重新生成,并在每次按钮单击时应用到一个新的随机值。

然后我的问题是如何在视图开始时生成随机值,然后保持直到用户正确猜到该值。

我的尝试是重新定位:

int answer = 0;
answer = arc4random() % 100 + 1;

到页面的开头,但是当稍后在页面上调用该方法时,我收到错误消息,指出answer 缺少标识符。感谢您的帮助,非常感谢。

【问题讨论】:

    标签: ios button random int modulus


    【解决方案1】:

    我认为问题是因为您将随机生成 sn-p 放在您的 IBAction 中,正如您在评论中所述:

    这是获取字段中提交的值的方法

    这意味着guessNow:sender中的代码将在用户每次点击按钮时被触发,这意味着每次用户提交一个没有意义的猜测时你都会生成一个随机数。

    //this is the method which takes the value submitted in the field and changes the label display after the user clicks the guess now button
    
    - (IBAction)guessNow:(id)sender {
    
    //set the random siri guess value between 1 and 100
    
    int answer = 0;
    answer = arc4random() % 100 + 1;
    
    self.usersGuess = self.guessNumberField.text;
    

    您应该将该代码块放在 viewDidLoad() 中并将属性 _answer 添加到您的 .h

    这是一个快速的解决方案,我没有在 XCode 上写这个,所以可能有语法错误

    在您的 .h 中,添加

    @property (strong) int _answer;
    

    在您的 .m 中,将其从guessNow:sender 中删除

    int answer = 0;
    answer = arc4random() % 100 + 1;
    

    并将其添加到您的 viewDidLoad()

    answer = arc4random() % 100 + 1;
    

    您可能还想添加另一个按钮来重置随机数,所以我会说将随机数生成隔离到您的 .m 中这样的私有方法

    - (void)generateRandomNumber
    {
        self.answer = arc4random() % 100 + 1;
    }
    

    因此,您可以在 viewDidLoad() 中使用此方法生成初始随机数并将其用于重置按钮(如果有)

    希望对你有帮助。

    【讨论】:

    • 谢谢。我已经尝试过了,但我从 .h property with retain or strong must be of object type 收到了这条消息。所以我将属性设置为@property (strong) NSObject _answer;。这给了我一个undeclared identifier 在我的.m 中为answeranswer = arc4random() % 100 + 1;
    • 我提到我手边没有IDE,很抱歉,我的错误,你不需要strong for int。试试这个,在你的 .h 中,在 @interface 行之后,输入 { int _answer; }
    • 感谢您在这个 Evan 上坚持我。我已经尝试过了,但answer = arc4random() % 100 + 1; 仍然给了我一个未声明的标识符。
    • 如果您将“int _answer”放在 .h 中,请务必在 .m 中使用“_answer”,而不仅仅是“answer”
    猜你喜欢
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多