iOS 虛擬鍵盤無原生「完成/上一項/下一項」工具條,每個輸入框都要單獨處理 returnKeyType、delegate、resignFirstResponder,代碼分散、體驗不一致。
UITextField/UITextView
// KeyBoardToolBar.h
@interface KeyBoardToolBar : NSObject
@property (nonatomic, strong) UIToolbar *toolbar;
@property (nonatomic, strong) NSArray *textFields;
@property (nonatomic, assign) BOOL showNavigationButtons;
@property (nonatomic, assign) BOOL inNavigationController;
@property (nonatomic, weak) UITextField *currentField;
+ (instancetype)sharedInstance;
- (void)configureWithTextFields:(NSArray *)fields
showNavigation:(BOOL)showNav
inNavigationController:(BOOL)inNav;
- (void)showForField:(UITextField *)field;
- (void)dismiss;
@end
// KeyBoardToolBar.m
@implementation KeyBoardToolBar
+ (instancetype)sharedInstance {
static KeyBoardToolBar *instance;
static dispatch_once_t once;
dispatch_once(&once, ^{ instance = [[self alloc] init]; });
return instance;
}
- (instancetype)init {
if (self = [super init]) {
// 工具條
_toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
_toolbar.barStyle = UIBarStyleBlackTranslucent;
// 按鈕
UIBarButtonItem *prev = [[UIBarButtonItem alloc] initWithTitle:@"上一項" style:UIBarButtonItemStylePlain target:self action:@selector(prevField)];
UIBarButtonItem *next = [[UIBarButtonItem alloc] initWithTitle:@"下一項" style:UIBarButtonItemStylePlain target:self action:@selector(nextField)];
UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismiss)];
_toolbar.items = @[prev, next, flex, done];
_showNavigationButtons = YES;
_inNavigationController = YES;
}
return self;
}
- (void)configureWithTextFields:(NSArray *)fields showNavigation:(BOOL)showNav inNavigationController:(BOOL)inNav {
_textFields = fields;
_showNavigationButtons = showNav;
_inNavigationController = inNav;
// 為每個輸入框設置 inputAccessoryView
for (UITextField *tf in fields) {
tf.inputAccessoryView = _toolbar;
tf.delegate = self; // 需遵循 UITextFieldDelegate
}
}
- (void)showForField:(UITextField *)field {
_currentField = field;
[self updateButtonStates];
}
- (void)dismiss {
[_currentField resignFirstResponder];
_currentField = nil;
}
- (void)prevField {
NSUInteger idx = [_textFields indexOfObject:_currentField];
if (idx != NSNotFound && idx > 0) {
UITextField *prev = _textFields[idx - 1];
[prev becomeFirstResponder];
}
}
- (void)nextField {
NSUInteger idx = [_textFields indexOfObject:_currentField];
if (idx != NSNotFound && idx < _textFields.count - 1) {
UITextField *next = _textFields[idx + 1];
[next becomeFirstResponder];
}
}
- (void)updateButtonStates {
NSUInteger idx = [_textFields indexOfObject:_currentField];
BOOL hasPrev = (idx != NSNotFound && idx > 0);
BOOL hasNext = (idx != NSNotFound && idx < _textFields.count - 1);
self.toolbar.items[0].enabled = hasPrev && _showNavigationButtons;
self.toolbar.items[1].enabled = hasNext && _showNavigationButtons;
}
// UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
[self showForField:textField];
}
@end
// ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *fields = @[_nameField, _emailField, _phoneField, _addressField];
[[KeyBoardToolBar sharedInstance] configureWithTextFields:fields
showNavigation:YES
inNavigationController:YES];
}
// 無需任何 delegate 代碼,自動生效
final class KeyboardToolbar: NSObject {
static let shared = KeyboardToolbar()
private let toolbar = UIToolbar()
private weak var fields: [UITextField]?
private weak var current: UITextField?
private override init() {
super.init()
toolbar.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44)
toolbar.barStyle = .blackTranslucent
let prev = UIBarButtonItem(title: "上一項", style: .plain, target: self, action: #selector(prev))
let next = UIBarButtonItem(title: "下一項", style: .plain, target: self, action: #selector(next))
let flex = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(dismiss))
toolbar.items = [prev, next, flex, done]
}
func configure(fields: [UITextField]) {
self.fields = fields
fields.forEach { $0.inputAccessoryView = toolbar; $0.delegate = self }
}
@objc private func prev() { move(-1) }
@objc private func next() { move(1) }
@objc private func dismiss() { current?.resignFirstResponder() }
private func move(_ delta: Int) {
guard let fields = fields, let current = current, let idx = fields.firstIndex(of: current) else { return }
let newIdx = idx + delta
guard fields.indices.contains(newIdx) else { return }
fields[newIdx].becomeFirstResponder()
}
}
extension KeyboardToolbar: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) { current = textField }
}
inputAccessoryView 同時支援 UITextField、UITextViewUIResponder.keyboardWillChangeFrameNotification 動態調整工具條位置(處理中文拼音面板、預測欄高度變化)