Dismiss keyboard on touch anywhere outside UITextField

前端 未结 8 1841
梦毁少年i
梦毁少年i 2020-11-27 17:22

I am developing an iPad app that has a large number of UIViewControllers, UITableViews (with cells with accessoryViews of UIText

8条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 17:26

    I actually really like Omar's technique - it works beautifully - but I've added a couple of lines in my case.

    - (void)keyboardDidShow:(NSNotification*)notification
    {
        UIButton *button = [[UIButton alloc] init];
    
        CGRect rect = self.view.bounds;
    
        button.frame = rect;
        button.backgroundColor = [UIColor blackColor];
    
        [button setAlpha:0.5f];
        button.tag = 111;
        UIView *currentResponder = [self.view findFirstResponder];
    
        [self.view bringSubviewToFront:currentResponder];
    
        if (currentResponder == _descriptionTextView) [_descriptionTextView setTextColor:[UIColor whiteColor]];
    
        [button addTarget:currentResponder action:@selector(resignFirstResponder) forControlEvents:UIControlEventTouchUpInside];
    
        [self.view insertSubview:button belowSubview:currentResponder];
    }
    

    I've added three lines to his solution (see above):

    1. Set the alpha of the button to 0.6, so that I can see some of my viewController behind it.
    2. Bring the currentResponder to the front, so that none of my other views are in front of the button.
    3. Switch the colour of my UITextView so that the text is clearer (my UITextView has a clear background, so the text wasn't showing clearly).

    Anyway, only minor changes, but hopefully these help. Thanks Omar.

提交回复
热议问题