萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 修改鍵盤顏色:僅支援數字鍵盤的 Appearance 方案

核心結論:系統鍵盤外觀高度受限

iOS **不提供公開 API** 修改系統鍵盤顏色。僅有**一種情況**可行:

  • 鍵盤類型為 **Number Pad** (`UIKeyboardTypeNumberPad`) 或 **Phone Pad** (`UIKeyboardTypePhonePad`)
  • 設定 `UITextField` 的 `keyboardAppearance = UIKeyboardAppearanceAlert` (深色風格)

其他鍵盤類型 (Default, Email, URL, Twitter 等) **完全無法修改顏色**,必須自製鍵盤。

代碼實現:運行時遍歷視圖層級 (Hack 方案,不穩定)

原文提供的方案利用私有視圖類 `UIPeripheralHostView`,**不保證未來版本相容**,**可能導致 App Store 拒審**,僅供研究參考:


- (void)textFieldDidBeginEditing:(UITextField *)textField {
    // 僅對數字鍵盤嘗試
    if (textField.keyboardType != UIKeyboardTypeNumberPad && 
        textField.keyboardType != UIKeyboardTypePhonePad) {
        return;
    }
    
    // 遍歷所有 Window 的子視圖
    for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
        for (UIView *view in window.subviews) {
            // 私有類名,版本間可能變更
            if ([[NSString stringWithUTF8String:object_getClassName(view)] isEqualToString:@"UIPeripheralHostView"]) {
                view.backgroundColor = [UIColor redColor]; // 任意顏色
                break;
            }
        }
    }
}

正規軍方案:自定義鍵盤 (Input View)

完全可控、App Store 安全、支援任意樣式

步驟 1:建立自定義鍵盤 View (XIB 或代碼)


// CustomKeyboardView.xib: 包含按鈕網格、完成鍵、刪除鍵
// File's Owner 設為 CustomKeyboardView 類
@interface CustomKeyboardView : UIView
@property (weak) id targetInput;
- (IBAction)keyTapped:(UIButton *)sender;
- (IBAction)backspaceTapped:(id)sender;
- (IBAction)doneTapped:(id)sender;
@end

步驟 2:實現按鍵邏輯


- (IBAction)keyTapped:(UIButton *)sender {
    NSString *char = sender.titleLabel.text;
    [self.targetInput insertText:char];
}

- (IBAction)backspaceTapped:(id)sender {
    [self.targetInput deleteBackward];
}

- (IBAction)doneTapped:(id)sender {
    [self.targetInput resignFirstResponder];
}

步驟 3:指定給 UITextField


- (void)viewDidLoad {
    [super viewDidLoad];
    
    CustomKeyboardView *keyboard = [[NSBundle mainBundle] loadNibNamed:@"CustomKeyboardView" owner:nil options:nil].firstObject;
    keyboard.targetInput = self.textField;
    
    self.textField.inputView = keyboard; // 替換系統鍵盤
    self.textField.inputAccessoryView = nil; // 可選:額外工具列
}

第三方成熟鍵盤庫推薦

  • IQKeyboardManager:自動處理鍵盤遮擋、工具列、Done 按鈕,**零代碼接入**
  • KeyboardKit:Swift 純粹、高度可定製、支援 SwiftUI
  • InputView:輕量級自定義鍵盤容器

總結建議

需求推薦方案
數字/電話鍵盤深色風格`keyboardAppearance = UIKeyboardAppearanceAlert` (官方、安全)
自定義顏色/佈局/功能自製 `inputView` + `IQKeyboardManager` 輔助
全 App 統一鍵盤體驗集成 `IQKeyboardManager` 啟用 `enableAutoToolbar`
特殊輸入(表情、符號、自定義佈局)自製鍵盤 View + `UITextDocumentProxy` 協議

切記:不要在上架 App 中使用私有 API 遍歷 `UIPeripheralHostView`,風險極高且效果不穩定。

copyright © 萬盛學電腦網 all rights reserved