-1

I am an Objective-C beginner and I made a guessing game. The game generates a random integer between 1 and 10 (inclusively) and the user must guess the number. The game then continues to verify whether or not the guess was correct with hints saying "Higher" or "Lower".

The game works fine. I included a delegate to remove the keyboard when the UITextField is used. I don't know what the problem is. I have looked all over stack overflow for how to do this, but the solutions all seem to include what I already have.

//  GGameViewController.h
#import <UIKit/UIKit.h>

@interface GGameViewController : UIViewController<UITextFieldDelegate>
{
}

@end

//  GGameViewController.m

#import "GGameViewController.h"

@interface GGameViewController ()
@property (weak, nonatomic) IBOutlet UITextField *inputTxtField;
@property (weak, nonatomic) IBOutlet UILabel *lblHints;
@property int r;
- (IBAction)btnGuess:(id)sender;

@end

@implementation GGameViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.inputTxtField.delegate = self;
    self.r     = (arc4random() % 10) + 1;//Got this from stackoverflow at http://stackoverflow.com/questions/510367/how-do-i-generate-random-numbers-on-the-iphone
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL) textfieldShouldReturn: (UITextField *)textField{
    [textField resignFirstResponder ];
    return YES;
}
- (IBAction)btnGuess:(id)sender {
    int guess = [self.inputTxtField.text intValue];
    NSString *response = @" ";

    if(guess == self.r){
        response = @"You got it!";
        self.inputTxtField.userInteractionEnabled = NO;//Got this from stackoverflow at http://stackoverflow.com/questions/5947965/ios-uitextfield-disabled
        }
    else if(guess < self.r)
        response = @"Higher";
    else if(guess > self.r)
        response = @"Lower";

    self.lblHints.text = [[NSString alloc] initWithFormat: @"%@",response];
}
@end
Black Frog
  • 11,595
  • 1
  • 35
  • 66

1 Answers1

0

If you copied this code from your editor, and the signature of the delegate callback is indeed

- (BOOL) textfieldShouldReturn: (UITextField *)textField{

then your problem is a matter of case sensitivity. The 'f' in textfield should be capitalized, like so:

- (BOOL) textFieldShouldReturn: (UITextField *)textField{

armcknight
  • 149
  • 6
  • Thanks a lot, sixstringtheory! That fixed it. Why was that the problem? Isn't textFieldShouldReturn a custom method that could be spelled any way I want it to be? – Timothy Nguyen Sep 06 '14 at 17:23
  • The problem was just the capitalization. Objective-C is always case-sensitive, so `textfieldShouldReturn` is not the same as `textFieldShouldReturn`, the latter being the delegate method defined for UITextField. Glad it's working now! – armcknight Sep 07 '14 at 19:21