Search code examples
iphoneipadkeyboardipodiphone-softkeyboard

iPhone/iPad Keyboard Dimming


I am writing a universal app that will be used primarily at night. I will need to display a keyboard but do not want the light colors of the keyboard to blind the user and/or spoil their night vision. I do not want to have to go through the trouble to creating a custom keyboard so I thought a solution might be to place a UIView over the keyboard and give it a black background color with an alpha of 0.5 or something however, I can not figure out how to get a UIView to cover the keyboard. Does anyone know how to do this? Does Apple allow this?


Solution

  • The keyboard is found as a subview of a new window that is added when it appears. Finding it is a little hacky and fragile (will need checking at new iOS versions, as it has changed before) but it does work and it is allowed (I do exactly this for a night mode in an app that is on the app store).

    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1]; // This assumes you aren't adding any new windows yourself
    
    for(UIView *keyboard in tempWindow.subviews) 
    {
        if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES) // This was different in an earlier version of iOS, and may well change again in the future!
        {
            [keyboard addSubview:maskView];
            break;
        }
    }
    

    This is done inside the method that responds to the UIKeyboardDidShowNotification object. I've not tried it on the iPad, this is iPhone code only.

    The mask view is, as you say, just a plain view with a black background and some transparency. You can also use the alert keyboard style which gives a black space in between the keys.

    This method does not prevent the little key flashes (the larger keys that pop up when you tap a key) from being at full brightness, unfortunately.