2010-12-03 69 views
0

在我的視圖中,我有3個UITextField,對於他們每個我創建了一個用於鍵盤的accessoryView,如apple所解釋的。ResignFirstResponder from Keyboard AccessoryView按鈕

在我的accessoryView中,我添加了一個必須調用函數「CloseKeyboard」的按鈕。在這個函數中,我找不到一種方法來截取鍵盤正在寫入的UITextField,並且我需要調用ResignFristResponder。

要在一個字段添加accessoryView的我寫的代碼

if (field1.inputAccessoryView == nil) { 
    field1.inputAccessoryView = [self createInputAccessoryView]; 
} 
if (field2.inputAccessoryView == nil) { 
    field2.inputAccessoryView = [self createInputAccessoryView]; 
} 
if (field3.inputAccessoryView == nil) { 
    field3.inputAccessoryView = [self createInputAccessoryView]; 
} 

這裏createInputAccessory功能:

-(UIView *)createInputAccessoryView { 

    CGRect accessFrame = CGRectMake(0.0, 0.0, 20.0, 55.0); 

    UIView *inputAccessoryView = [[UIView alloc] initWithFrame:accessFrame]; 

    UIButton *compButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

    compButton.frame = CGRectMake(250.0, 10.0, 60.0, 40.0); 

    [compButton setTitle: @"Close" forState:UIControlStateNormal]; 

    [compButton addTarget:self action:@selector(CloseKeyboard:) 

         forControlEvents:UIControlEventTouchUpInside]; 

    [inputAccessoryView addSubview:compButton]; 

return inputAccessoryView; } 

我怎樣才能實現「CloseKeyboard」功能,能夠從積極的UITextField到resignFirstResponder ?

謝謝你的幫助!

回答

1

由於iOS的2.0及更高版本,也可以隱藏鍵盤,而無需跟蹤當前主動控制一個簡單的方法,或遍歷所有可用的控件,或使用UITextFieldDelegate

[self.view endEditing:YES] 

從文檔:

endEditing:

使視圖(或它的嵌入文本字段中的一個),以 辭職第一響應者的狀態。

- (BOOL)endEditing :(BOOL

參數

指定YES迫使第一響應辭職,不管是否願意做這樣 。

返回值
YES如果視圖辭職第一響應狀態或NO,如果它沒有。

討論
該方法着眼於當前視圖及其子視圖 層次結構是當前的第一響應者的文本字段。如果 找到一個,它會要求該文本字段作爲第一響應者辭職。如果 force參數設置爲YES,則甚至不會詢問文本字段; 它被迫辭職。

0

作爲第一個解決方案,我嘗試使用此實現,其中我每次強制field1成爲firstResponder並且比我辭職。

-(void) closeFunction:(id)sender{ 
    [field1 becomeFirstResponder]; 
    [field1 resignFirstResponder]; 
} 

但是,這是一個解決辦法......沒有辦法了:P