2010-08-03 43 views
0

我曾經使用以下代碼在UIKeyboard上方添加UIToolbar並將其附加到它。我剛剛切換到iPhone OS 4,我意識到它不再工作。UIKeyboard未添加到UIWindow子視圖

for (UIWindow *keyboardWindow in [[UIApplication sharedApplication] windows]) { 
    for (UIView *keyboard in [keyboardWindow subviews]) { 

     //print all uiview descriptions 

     if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES) { 
      .. Some code to attach the UIToolbar 
     } 
    } 
} 

我意識到代碼沒有進入if語句。我嘗試打印出所有UIView描述,並且我看不到與UIKeyboard相關的任何內容。代碼在OS 3.0和3.1中工作正常。那麼有沒有人對此有所瞭解?

回答

0

由於您依賴的是無證行爲,因此它不再適用於4.0。改爲使用您的視圖的inputAccessoryView屬性,這是在OS 3.2+中執行此操作的已記錄方式。

1

你應該嘗試使用這個下面的代碼:

- (BOOL) findKeyboard:(UIView *) superView; 
{ 
    UIView *currentView; 
    if ([superView.subviews count] > 0) { 
     for(int i = 0; i < [superView.subviews count]; i++) 
     { 

      currentView = [superView.subviews objectAtIndex:i]; 
      NSLog(@"%@",[currentView description]); 
      if([[currentView description] hasPrefix:@"<UIKeyboard"] == YES) 
      { 

       NSLog(@"Find it"); 
       //add toolbar here 

       UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, -40, 100, 40)]; 
       UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Test button" style:UIBarButtonItemStyleBordered target:self action:@selector(buttonClicked:)]; 
       NSArray *items = [[NSArray alloc] initWithObjects:barButtonItem, nil]; 
       [toolbar setItems:items]; 
       [items release]; 
       [currentView addSubview:toolbar]; 

       return YES; 
      } 
      if ([self findKeyboard:currentView]) return YES; 
     } 
    } 

    return NO; 

} 

-(void) checkKeyBoard { 
    UIWindow* tempWindow; 

    for(int c = 0; c < [[[UIApplication sharedApplication] windows] count]; C++) 
    { 
     tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:c]; 
     if ([self findKeyboard:tempWindow]) 
      NSLog(@"Finally, I found it"); 
    } 
} 

- (void)keyboardWillShow:(NSNotification *)note { 
    [self performSelector:(@selector(checkKeyBoard)) withObject:nil afterDelay:0]; 
} 

而且你還需要添加該代碼在AppDelegate中發揮作用didFinishLaunchingWithOptions:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; 
相關問題