кнопка «Готово» не отображается в проблеме iOS 9 с цифровой панелью

этот код работает в ios 6,7,8, но этот метод вызывается в ios 9, но он не виден. на цифровой клавиатуре. вот мой код.

#import "ViewController.h"
#define TAG_BUTTON_DONE 67125
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)keyboardDidShow:(NSNotification *)note {
    [self addButtonToKeyboard];
}
- (void)addButtonToKeyboard{
    //NSLog(@"addButtonToKeyboard");
    //jenish



    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        // create custom button
        UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        doneButton.frame = CGRectMake(0, 163, 106, 53);
        doneButton.adjustsImageWhenHighlighted = NO;
        [doneButton setTag:TAG_BUTTON_DONE];
        //[doneButton setImage:[UIImage imageNamed:@"doneup.png"] forState:UIControlStateNormal];
        //[doneButton setImage:[UIImage imageNamed:@"donedown.png"] forState:UIControlStateHighlighted];
        [doneButton setTitle:@"Done" forState:UIControlStateNormal];
        [doneButton setTintColor:[UIColor blackColor]];
        [doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];

        // locate keyboard view
        int windowCount = (int)[[[UIApplication sharedApplication] windows] count];
        if (windowCount < 2) {
            return;
        }


        UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
        UIView* keyboard;

        for(int i=0; i<[tempWindow.subviews count]; i++) {
            keyboard = [tempWindow.subviews objectAtIndex:i];
            // keyboard found, add the button
            if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES){
                [keyboard addSubview:doneButton];
            }
            else if([[keyboard description] hasPrefix:@"<UIInputSetContainerView"] == YES){
                for(int j = 0 ; j < [keyboard.subviews count] ; j++) {
                    UIView* hostkeyboard = [keyboard.subviews objectAtIndex:j];
                    if([[hostkeyboard description] hasPrefix:@"<UIInputSetHost"] == YES){
                        [hostkeyboard addSubview:doneButton ];
                        [hostkeyboard bringSubviewToFront:doneButton];

                    }
                }
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [keyboard addSubview:doneButton];
                });


            }
        }
    }
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch * touch = [touches anyObject];
    if(touch.phase == UITouchPhaseBegan) {
        [self.tf resignFirstResponder];
    }
}
@end

затем вам нужно уйти на задний план и выйти на передний план, он будет виден на несколько секунд, а затем скроется. пожалуйста, помогите мне. Спасибо


person jenish    schedule 14.10.2015    source источник


Ответы (3)


Изменять

UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];

To :

UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] lastObject];
person The Bird    schedule 09.11.2015
comment
Да, это работает, я показываю кнопку на своем экране, но я не обрабатываю событие этой кнопки. используя тот же код с изменением предлагаемых изменений. - person jenish; 09.11.2015

Хорошо, вот простое исправление для отображения кнопки «Готово» в приложении как в iOS 9, так и в iOS 8 и ниже, адаптированное к вашему вопросу. Это можно было наблюдать после запуска приложения и просмотра его через «Иерархию представлений» (т. е. щелкнуть значок «Иерархия представлений» в строке заголовка области отладки, когда приложение запущено на устройстве и проверить представления в раскадровке). ), что клавиатура представлена ​​в разных окнах в iOS 9 по сравнению с iOS 8 и более ранними версиями, и это необходимо учитывать.

Сначала мы объявляем глобальное свойство 'buttonDone' типа UIButton и используем его в нашем файле реализации, как показано ниже:

#import "ViewController.h"
#define TAG_BUTTON_DONE 67125

@interface ViewController ()
    @property (nonatomic, strong) UIButton *doneButton;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void)keyboardDidShow:(NSNotification *)note {
[self addButtonToKeyboard];
}

- (id)addButtonToKeyboard
{
if (!doneButton)
{
// create custom button
    doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 163, 106, 53);
    doneButton.adjustsImageWhenHighlighted = NO;
    [doneButton setTag:TAG_BUTTON_DONE];
    //[doneButton setImage:[UIImage imageNamed:@"doneup.png"] forState:UIControlStateNormal];
    //[doneButton setImage:[UIImage imageNamed:@"donedown.png"] forState:UIControlStateHighlighted];
    [doneButton setTitle:@"Done" forState:UIControlStateNormal];
    [doneButton setTintColor:[UIColor blackColor]];  
}

NSArray *windows = [[UIApplication sharedApplication] windows];
//Check to see if running below iOS 9,then return the second window which bears the keyboard   
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 9.0) {
    return windows[windows.count - 2];
}
else {
    UIWindow* keyboardWithDoneButtonWindow = [ windows lastObject];
    return keyboardWithDoneButtonWindow;
    }

[buttonDone addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];

}

Реализуйте метод селектора 'doneButton', чтобы выполнять любое действие, которое вы хотите, например, менять местами или переключать клавиатуры между цифровыми панелями или по умолчанию, аутентифицировать приложение и т. д. И вы должны быть золотыми!

person Vick Swift    schedule 27.11.2015

Прежде всего мы объявляем новую переменную:

@property (strong, nonatomic) UIButton *doneButton;

Инициализация кнопки вызова в viewDidLoad:

- (void)setupDoneButton {
    if (!self.doneButton) {
        self.doneButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [self.doneButton addTarget:self action:@selector(tapGestureRecognizerAction) forControlEvents:UIControlEventTouchUpInside];
        self.doneButton.adjustsImageWhenHighlighted = NO;
        [self.doneButton setTitle:@"DONE" forState:UIControlStateNormal];
        [self.doneButton.titleLabel setFont:[UIFont systemFontOfSize:16.0]];
        [self.doneButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.doneButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    }
}

Показать кнопку в методе keyboardDidShow или textFieldDidBeginEditing:

- (void)addDoneButtonToKeyboard {
    dispatch_async(dispatch_get_main_queue(), ^{
    UIWindow *keyboardWindow = [[[UIApplication sharedApplication] windows] lastObject];
    CGFloat buttonWidth = CGRectGetWidth(keyboardWindow.frame)/3;
    self.doneButton.frame = CGRectMake(0.f, CGRectGetHeight(keyboardWindow.frame) - 53, buttonWidth, 53);
    [keyboardWindow addSubview:self.doneButton];
    [keyboardWindow bringSubviewToFront:self.doneButton];
    });
}

Чем удалить кнопку в методе keyboardWillHide или textFieldDidEndEditing:

    [self.doneButton removeFromSuperview];

Это работает как на iOS8, так и на iOS9.

person landonandrey    schedule 09.09.2016