2014-09-05 94 views
-1

我是Objective-C初學者,我做了一個猜謎遊戲。遊戲產生1到10之間的隨機整數(包含),用戶必須猜出數字。然後遊戲繼續驗證猜測是否正確,提示「更高」或「更低」。UITextFieldDelegate無法正常工作

遊戲工作正常。當使用UITextField時,我包括一個委託來移除鍵盤。我不知道問題是什麼。 我已經看過遍佈堆棧溢出了,如何做到這一點,,但解決方案似乎都包含我已有的東西。

// 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 
+2

嘗試'[self.view endEditing:YES];'代替'[文本字段resignFirstResponder];'。 – GlennRay 2014-09-05 17:41:38

+0

一切看起來不錯。順便說一句...你使用什麼鍵盤類型/風格?它有一個完成/任何返回類型按鈕?如果您使用的是「數字鍵盤」,則默認情況下它不會有返回按鈕。 – staticVoidMan 2014-09-05 17:55:48

+0

您是否在IB中將'inputTextField'與相應的'UITextField'連接起來了? – neutrino 2014-09-05 20:47:02

回答

0

如果您複製從編輯器的代碼,並委託回調的簽名確實是

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

那麼你的問題是區分大小寫的問題。在textfield的 'f' 應該大寫,像這樣:

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

+0

非常感謝,六絃理論!這解決了它。爲什麼是這個問題?是不是textFieldShould返回一個自定義的方法,可以拼寫我想要的任何方式? – 2014-09-06 17:23:54

+0

問題只是大寫。 Objective-C總是區分大小寫,所以'textfieldShouldReturn'與'textFieldShouldReturn'不一樣,後者是爲UITextField定義的委託方法。很高興現在正在工作! – sixstringtheory 2014-09-07 19:21:02