按下按钮后如何返回循环

时间:2014-02-01 19:42:36

标签: ios loops button

我正在上一个在线课程,其中一个问题是你建立了一个简单的数字猜谜游戏。这很容易。但是,我想修改它以限制猜测的数量。这将需要一个允许猜测次数的循环。

当我尝试这个时,代码进入按钮按下操作并且永远不会返回循环。我已经尝试了所有我知道的工作,google搜索没有帮助,而且教师还没有回答我4天前发布的问题!

简而言之,在完成按钮按下的代码后,如何让代码返回循环?

在这里,我想做的是:

generate random number

for x = 1 to 6

    get user guess in text field

    press button to check if correct

    if correct

        do something

    else

        continue loop for another guess 

    x = x+1 

1 个答案:

答案 0 :(得分:0)

你无法做你想做的事。

用户界面是一种事件驱动的活动 - 由于用户键入textField或点击按钮而发生的事情。处理UI的代码分布在处理事件的响应例程中,您必须弄清楚在哪里可以执行您想要执行的操作的每个部分。这可能令人抓狂!

一般的答案是处理事件的代码分布在多个方法中,您必须具有某种共享状态,以便每个事件响应都可以知道该怎么做。某些代码在某处开始一轮游戏并初始化猜测次数。 textField委托例程让用户猜测并将其存储在实例变量或属性中。当用户点击按钮时,按钮响应代码可以检查该属性中的答案并跟踪猜测次数。

具体来说,这里有一些伪代码可以完成您在问题中提出的建议:

@property (strong, nonatomic) NSString *currentGuess;
@property (nonatomic) int numberOfGuesses;


- (void) startNewRound {
    ...
    // some code that gets ready for the user to guess
    generate random number
    // initialize the number of guesses where button code can get at it
    self.numberOfGuesses = 0;
    ...
}

// This method is called when the user finishes typing
// a guess in the text field as a result of the user pressing Return
// (or however you manage the data entry).  The parameter is whatever
// the user typed as a guess.
- (void) userEnteredAGuess:(NSString *)guess
    // put the guess where the button-event code can get at it
    self.currentGuess = guess;
}

// This is the method that gets run when the user taps the
// "Check the Guess" button
- (IBACTION) tapButton:(UIButton *)sender {
    if (the guess in self.currentGuess is correct...) {
        // Do whatever you do when the guess is correct
    } else {
        // Do whatever you do when the guess is wrong
    }
    self.numberOfGuesses += 1;
    if (self.numberOfGuesses > guessLimit) {
        // Exceeded guess limit
        // Do whatever should happen --
        // re-initialize the guesses, decrement score, ... whatever
        // maybe...
        [self startNewRound];
    }
}