系統預設的數字鍵盤(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];
}
}
}
}
}
<UIInputSetContainerView 開頭,因此判斷邏輯中必須加入這一項。SCREEN_SIZE.height 計算 Y 座標)。透過這種方式,我們就能為數字鍵盤補上一顆「完成」按鈕,讓使用者可以順暢地結束輸入並收起鍵盤。