iOS **不提供公開 API** 修改系統鍵盤顏色。僅有**一種情況**可行:
其他鍵盤類型 (Default, Email, URL, Twitter 等) **完全無法修改顏色**,必須自製鍵盤。
原文提供的方案利用私有視圖類 `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;
}
}
}
}
完全可控、App Store 安全、支援任意樣式
// 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
- (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];
}
- (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; // 可選:額外工具列
}
| 需求 | 推薦方案 |
|---|---|
| 數字/電話鍵盤深色風格 | `keyboardAppearance = UIKeyboardAppearanceAlert` (官方、安全) |
| 自定義顏色/佈局/功能 | 自製 `inputView` + `IQKeyboardManager` 輔助 |
| 全 App 統一鍵盤體驗 | 集成 `IQKeyboardManager` 啟用 `enableAutoToolbar` |
| 特殊輸入(表情、符號、自定義佈局) | 自製鍵盤 View + `UITextDocumentProxy` 協議 |
切記:不要在上架 App 中使用私有 API 遍歷 `UIPeripheralHostView`,風險極高且效果不穩定。