iPhone 與 iPod touch 的鍵盤配色其實可以透過程式碼調整,讓它更貼近 App 的整體視覺風格。不過這個做法有幾個前提,先看說明再看程式碼。
keyboardAppearance 設為 UIKeyboardAppearanceAlert。第二點很容易被忽略:預設的 UIKeyboardAppearanceDefault 是淺色系統鍵盤,只有切到 Alert 樣式後,鍵盤背景才會變成深色半透明,此時改背景色才看得出效果。
原理是在鍵盤出現的瞬間,沿著 window 的視圖階層找到名為 UIPeripheralHostView 的那層容器,再把它的背景色改掉:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
// 先把鍵盤樣式切為 Alert,改色才有效
textField.keyboardAppearance = UIKeyboardAppearanceAlert;
NSArray *ws = [[UIApplication sharedApplication] windows];
for (UIView *w in ws) {
NSArray *vs = [w subviews];
for (UIView *v in vs) {
if ([[NSString stringWithUTF8String:object_getClassName(v)]
isEqualToString:@"UIPeripheralHostView"]) {
v.backgroundColor = [UIColor redColor];
}
}
}
}
UIPeripheralHostView 是系統未公開的私有類別名稱。硬去比對這個字串有兩個風險:一是 Apple 未承諾保留這個類別名,iOS 版本一升就可能改名或改變視圖結構,導致改色失效;二是遍歷 [[UIApplication sharedApplication] windows] 去搜尋私有視圖,在審核時可能被判定為使用私有 API。
如果你的目的只是「讓鍵盤顏色不要那麼突兀」,其實有兩個更安全的選項:把 keyboardAppearance 設為 Alert 就能得到深色鍵盤,不需任何 hack;或者乾脆自製鍵盤——從 iOS 8 起,只要建立一個 UIInputViewController 的子類別,就能完全自訂鍵盤的外觀與按鍵佈局,這才是官方支援的做法。