views:

202

answers:

2

I used to use the following code to add a UIToolbar just above the UIKeyboard and being attached to it. I just switched to the iPhone OS 4 and I realized that it's not working anymore.

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
    }   
}

}

I realized that the code does not get into the if statement. I tried printing out all UIView descriptions just above the if and I could not see anything related to UIKeyboard. The code was working fine in OS 3.0 and 3.1. So does anyone have any idea about it?

A: 

Since you are relying on undocumented behavior, it should be no surprise that it does not work in 4.0 anymore. Use your views' inputAccessoryView property instead, which is the documented way to do this in OS 3.2+.

Ole Begemann
A: 

You should try to use this below code:

  - (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];
}

And you also need to add this code to function didFinishLaunchingWithOptions in AppDelegate:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
Hung Dang