2011-09-07 72 views
7

我的代碼:如何將文本字段添加到inputAccessoryView,使TextView的第一個響應者

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    CGRect rectFake = CGRectZero; 

    UITextField *fakeField = [[UITextField alloc] initWithFrame:rectFake]; 

    [self.view addSubview:fakeField]; 

    UIView *av = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 0.0, 39.0)]; 

    av.backgroundColor = [UIColor darkGrayColor]; 

    CGRect rect = CGRectMake(200.0, 4.0, 400.0, 31.0); 

    UITextField *textField = [[UITextField alloc] initWithFrame:rect]; 

    textField.borderStyle = UITextBorderStyleRoundedRect; 

    textField.font = [UIFont systemFontOfSize:24.0]; 

    textField.delegate = self; 

    [av addSubview:textField]; 

    fakeField.inputAccessoryView = av; 

    [fakeField becomeFirstResponder]; 

} 

我試圖在最後添加

[textField becomeFirstResponder] 

,但它確實沒有工作。

另一個委託方法在按下ENTER按鈕時隱藏鍵盤的問題也不起作用。

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

    [textField resignFirstResponder]; 

    return YES; 
} 
+0

試試這個UIView的* AV = [[UIView的頁頭] initWithFrame:方法CGRectMake( 0.0,0.0,320.0,39.0)]; –

+0

對不起,我沒有提到它適用於iPad,並且此視圖沿着鍵盤延伸,所以寬度沒有意義。 – Michael

回答

13

我正面臨同樣的挑戰。由於UITextField最初並未位於屏幕上,因此inputAccessoryView中的文本字段拒絕成爲第一響應者,因此您的(和我的初始)方法可能不起作用。

我的解決方案:檢查鍵盤(以及附件視圖)何時出現!

步驟1)偵聽通知(確保在您想要接收通知之前執行此代碼)。

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(changeFirstResponder) 
              name:UIKeyboardDidShowNotification 
              object:nil]; 

步驟2)當鍵盤出現,可以設置文本框在inputAccessoryView成爲第一個響應者:

-(void)changeFirstResponder 
{ 
    [textField becomeFirstResponder]; // will return YES; 
} 
+0

我試圖達到同樣的效果,你的想法聽起來像可能會奏效,但是你如何讓鍵盤出現在第一位呢? 我有一個UIButton按下時,我需要鍵盤才能在附件視圖中顯示文本字段。 – Darren

+0

@Darren我知道一個半髒解決方法,那就是已經在當前視圖中有一個(隱藏的)文本框,並使用按鈕操作來設置'[yourHiddenTextField becomeFirstResponder]' – Tom

+0

這正是我需要做的。 Thx – Darren

相關問題