您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS8 為數字鍵盤左下角添加「完成」按鈕

編輯:iOS 開發綜合

系統預設的數字鍵盤(Number Pad)並沒有回車或完成鍵,使用者輸入完畢後往往不知如何收起鍵盤。一個常見的解法,是在鍵盤左下角自訂一個「完成」按鈕。以下提供核心程式碼,並針對 iOS8 之後的變化做了適配。

- (void)addDoneButtonToNumPadKeyboard {
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    if (systemVersion < 8.0) {
        doneButton.frame = CGRectMake(0, 163, 106, 53);
    } else {
        doneButton.frame = CGRectMake(0, SCREEN_SIZE.height - 53, 106, 53);
    }
    doneButton.tag = NUM_PAD_DONE_BUTTON_TAG;
    doneButton.adjustsImageWhenHighlighted = NO;
    [doneButton setTitle:@"完成" forState:UIControlStateNormal];
    [doneButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];

    NSArray *windowArr = [[UIApplication sharedApplication] windows];
    if (windowArr != nil && windowArr.count > 1) {
        UIWindow *needWindow = [windowArr objectAtIndex:1];
        UIView *keyboard;
        for (int i = 0; i < [needWindow.subviews count]; i++) {
            keyboard = [needWindow.subviews objectAtIndex:i];
            NSLog(@"%@", [keyboard description]);
            if ([[keyboard description] hasPrefix:@"<UIPeripheralHostView"] == YES
                || [[keyboard description] hasPrefix:@"<UIKeyboard"] == YES
                || [[keyboard description] hasPrefix:@"<UIInputSetContainerView"] == YES) {
                UIView *doneButtonView = [keyboard viewWithTag:NUM_PAD_DONE_BUTTON_TAG];
                if (doneButtonView == nil) {
                    [keyboard addSubview:doneButton];
                }
            }
        }
    }
}

- (void)removeDoneButtonFromNumPadKeyboard {
    UIView *doneButton = nil;
    NSArray *windowArr = [[UIApplication sharedApplication] windows];
    if (windowArr != nil && windowArr.count > 1) {
        UIWindow *needWindow = [windowArr objectAtIndex:1];
        UIView *keyboard;
        for (int i = 0; i < [needWindow.subviews count]; i++) {
            keyboard = [needWindow.subviews objectAtIndex:i];
            if ([[keyboard description] hasPrefix:@"<UIPeripheralHostView"] == YES
                || [[keyboard description] hasPrefix:@"<UIKeyboard"] == YES
                || [[keyboard description] hasPrefix:@"<UIInputSetContainerView"] == YES) {
                doneButton = [keyboard viewWithTag:NUM_PAD_DONE_BUTTON_TAG];
                if (doneButton != nil) {
                    [doneButton removeFromSuperview];
                }
            }
        }
    }
}

注意事項

  1. iOS8 之後,鍵盤 view 的 description 變為以 <UIInputSetContainerView 開頭,因此判斷邏輯中必須加入這一項。
  2. iOS8 之後,鍵盤 view 的尺寸變成了整個螢幕大小,所以需要對按鈕的添加位置進行適配(如程式碼中透過 SCREEN_SIZE.height 計算 Y 座標)。

透過這種方式,我們就能為數字鍵盤補上一顆「完成」按鈕,讓使用者可以順暢地結束輸入並收起鍵盤。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved