2012-11-14 81 views
1

我學習OBJ-c和給自己創造,具有2 uitextfields一個應用程序的一個簡單的任務,label & button(按鈕總結2號和顯示結果在標籤中)。我做了這個應用程序,但我還沒有想出如何使textfields與「完成」按鈕&「僅數字」在一起進行交互。的UITextField與數字僅與鍵盤上的iPhone上的「完成」

下面是我的代碼:

#import UIKit/UIKit.h 

@interface ViewController : UIViewController 

@property IBOutlet UILabel *label; 
@property IBOutlet UITextField *textField1; 
@property IBOutlet UITextField *textField2; 
@property NSInteger textFieldInt1, textFieldInt2; 
@property NSString *textFieldStr1, *textFieldStr2; 

-(IBAction)button:(id)sender; 
-(IBAction)hideKeyboard:(id)sender; 

@end 


#import "ViewController.h" 

@interface ViewController() 
@end 

@implementation ViewController 

@synthesize label, textField1, textField2, textFieldInt1, textFieldInt2, textFieldStr1, textFieldStr2; 

-(IBAction)button:(id)sender { 
    textFieldInt1=[textField1.text integerValue]; 
    textFieldInt2=[textField2.text integerValue]; 
    label.text=[NSString stringWithFormat: @"%d", textFieldInt1+textFieldInt2]; 
    [self.view endEditing:YES]; 
} 



- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 

    [self.textField1 setReturnKeyType:UIReturnKeyDone]; 
    [self.textField2 setReturnKeyType:UIReturnKeyDone]; 

} 

-(IBAction)hideKeyboard:(id)sender 
{ 
    [self.view endEditing:YES]; 
} 

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range  replacementString:(NSString *)string { 
    if(![string intValue] && ![string isEqualToString:@""] && ![string isEqualToString:@"0"]) 
    { 
    return NO; 
    } else { 
    return YES; 
    } 
} 

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

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    [self.view endEditing:YES]; 
    [super touchesBegan:touches withEvent:event]; 
} 


@end 

而且我連接(在故事板)都textFieldshideKeyboard (didEndOnExit),並buttonbutton (touchUpInside)和所有網點(textfieldsbuttonlabel)。

問題是:numbers only輸入不適用於done。如果我使用delegate(新引用的故事板連接到兩個textfields出口)我得到numbers only輸入textfieldsdone按鈕不起作用(當我按下它在iPhone上沒有任何反應)。如果我不使用delegate我得到all characters輸入,但done正常工作(當我按下iPhone鍵盤隱藏)。

任何建議,我可能會做錯了什麼?

回答

0

落實UITextFieldDelegate方法:

// This is how we get rid of the keyboard. 
- (BOOL)textFieldShouldReturn:(UITextField *)textField { 
    //Do whatever you need to to save etc... 
    [textField resignFirstResponder]; 
    return NO; 
} 

這告訴鍵盤按下完成按鈕時隱藏。 務必將您的視圖控制器爲文本框代表: myTextField.delegate =自我; (可能是在viewDidLoad中)

+0

這是一個評論回覆評論有人發帖,然後刪除。由於原來的評論沒有了,我不能刪除這條評論,所以你會得到這個垃圾評論....很好。 – HackyStack

+0

我很抱歉我的英語,可能我沒有把我的問題弄清楚。我確實有「完成」按鈕,它可以正常工作(隱藏鍵盤),但不使用「僅限數字」輸入限制。這是我無法解決的問題。 –

+0

非常感謝你!它工作正常!我用你的代碼替換了我的方法(IBAction)hideKeyboard:(id)sender {[self.view endEditing:YES];},並將兩個文本字段與「委託」(新引用插座)相關聯。 –