我是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
嘗試'[self.view endEditing:YES];'代替'[文本字段resignFirstResponder];'。 – GlennRay 2014-09-05 17:41:38
一切看起來不錯。順便說一句...你使用什麼鍵盤類型/風格?它有一個完成/任何返回類型按鈕?如果您使用的是「數字鍵盤」,則默認情況下它不會有返回按鈕。 – staticVoidMan 2014-09-05 17:55:48
您是否在IB中將'inputTextField'與相應的'UITextField'連接起來了? – neutrino 2014-09-05 20:47:02