萬盛學電腦網

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

iOS 鍵盤工具條封裝:上一項/下一項/隱藏鍵盤、動畫彈出、任意輸入框適配

痛點

iOS 虛擬鍵盤無原生「完成/上一項/下一項」工具條,每個輸入框都要單獨處理 returnKeyType、delegate、resignFirstResponder,代碼分散、體驗不一致。

通用解決方案:KeyBoardToolBar 單例

核心功能

  • ✅ 自動隨鍵盤彈出/收回(動畫同步)
  • ✅ 「上一項」「下一項」在多輸入框間循環焦點
  • ✅ 「隱藏鍵盤」一鍵收起
  • ✅ 支援導航控制器內邊距自動調整
  • ✅ 一行代碼接入任意 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 代碼,自動生效

Swift 現代版(推薦新項目)


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 }
}

進階:支援 UITextView、自定義按鈕、鍵盤高度變化監聽

  • inputAccessoryView 同時支援 UITextField、UITextView
  • 監聽 UIResponder.keyboardWillChangeFrameNotification 動態調整工具條位置(處理中文拼音面板、預測欄高度變化)
  • 自定義按鈕:掃碼、語音輸入、表情鍵盤切換、模板插入
copyright © 萬盛學電腦網 all rights reserved