2016-04-21 86 views
1

我有兩個文本字段。點擊後,第一個顯示一個QWERTY鍵盤,第二個顯示選擇器。 我的問題是當我點擊我的第一個textField時,鍵盤正常顯示。現在,在我輸入任何東西之後,我直接想要點擊第二個textField,這是顯示選擇器,鍵盤應該消失,但鍵盤仍然存在。 我想單擊第二個textField時立即隱藏鍵盤。鍵盤不隱藏時點擊第二個文本字段

+0

第一點擊後第二文本字段被做self.view.endEditing則目前選擇器 –

+0

我沒有...但不工作 –

+0

..刪除textfild&使用按鈕爲什麼使用textfield –

回答

2

有兩種方式來實現這一點 -

第一:使用UITextFieldDelegate。 對於覺得─ 列出UITextFieldDelegate在您的視圖控制器的協議列表一樣,

@interface ViewController : UIViewController <UITextFieldDelegate> 

然後讓你的ViewController符合文本字段的委託,以實現像textFieldDidBeginEditing的方法,並textFieldDidEndEditing:

所以,去到viewDidLoad方法和符合的UITextField的協議喜歡 -

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.firstTextField.delegate = self; //assuming your first textfield's 
             //name is firstTextField 
    //Also give your first textfield a tag to identify later 

    self.firstTextField.tag = 1; 
} 

現在,你都設置爲實現委託方法。但是,要首先實現目標,需要使用UITextField實例來了解何時輸入firstTextField。因此,聲明UITextField類型的屬性。這樣做,在接口文件喜歡 -

@property(nonatomic, strong) UITextField *currentTextField; 

現在在textFieldDidBeginEditing委託方法中,firstTextField實例分配到currentTextField當您開始鍵入它喜歡 -

- (void)textFieldDidBeginEditing:(UITextField *)textField{ 
     if(textField.tag == 1){ 
      self.currentTextField = textField; 
     } 
} 

後,在textFieldDidEndEditing方法,檢查它是否是當前的文本框要從中走出來,並取消鍵盤喜歡 -

-(void)textFieldDidEndEditing:(UITextField *)textField{ 
      if(textField.tag == 1){ 
       [self.currentTextField resignFirstResponder]; 
      } 
      return YES; 
    } 

:您可以使用UIResponder。作爲ViewControllers從UIResponder繼承,你只需重寫方法 - touchesBegan:withEvent方法,一些喜歡 -

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
     [self.view endEditing:YES];// this will do the trick 
} 

在這種情況下,當你點擊了側的文本字段,鍵盤會自動消失。

+0

我做同樣的事情....但它不工作。 –

+0

您選擇了哪個選項,第一個還是第二個? – Natasha

+0

如果可能,發佈一些代碼片段。還可以通過左側面板上的連接檢查器張貼故事板的屏幕截圖。檢查你自己,如果你已經連接你的文本框和故事板上的插座。 – Natasha

2

使用UITextFieldDelegate組代表在ViewDidLoadself,然後把這個代碼

func textFieldDidEndEditing(textField: UITextField) 
{ 
    yourtextfieldname.resignFirstResponder() 
    return true 
} 
+0

我正在這樣做,但它不工作 –

1
Step 1 :- Code for ViewController.h :-             

//add UITextFieldDelegate just after UIViewController 

@interface ViewController : UIViewController<UITextFieldDelegate> 

Step 2 :- Code For ViewController.m :- 

//inside viewdidLoad write following code, where txtInput is outlet for input text field 

_txtInput.delegate = self; 

// Last Thing write following code just above @end 

-(BOOL)textFieldShouldReturn:(UITextField *)textField 
{ 
[textField resignFirstResponder]; 
return YES; 
} 

//that's it use this very simple way