📜  将 UIToolBar 添加到所有键盘 - Swift (1)

📅  最后修改于: 2023-12-03 15:09:32.863000             🧑  作者: Mango

将 UIToolBar 添加到所有键盘 - Swift

在 iOS 应用程序中,UIToolBar 是一种非常有用的控件,它可以为用户提供快速访问常用功能的按钮。在本文中,我们将学习如何将 UIToolBar 添加到所有键盘中。

步骤一:创建 UIToolBar

首先,我们需要创建我们的 UIToolBar。您可以在任何 ViewController 中创建它,或者单独的类中创建它以供在应用程序的不同部分使用。下面是一个简单的示例:

let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(doneButtonTapped))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolbar.items = [flexibleSpace, doneButton]

这将创建一个 UIToolBar,其中包含一个名为“完成”的按钮和灵活的空间。可以随意更改 doneButtonTapped() 方法以执行您希望在按钮单击时执行的任何操作。

步骤二:将 UIToolBar 添加到键盘

现在,我们可以将我们的 UIToolBar 添加到键盘中。要执行此操作,我们必须监听键盘出现的通知,然后将 UIToolBar 添加到键盘的输入辅助视图中。下面是实现此目的的代码:

首先,需要实现两个函数,分别是显示和隐藏UIToolBar的,比如:

@objc func keyboardWillShow(_ notification: Notification) {
    if let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect {
        let keyboardSize = keyboardFrame.size
        let screenHeight = UIScreen.main.bounds.size.height
        let toolbarHeight = self.toolbar.frame.size.height
        
        var safeAreaBottomInset: CGFloat = 0
        
        if #available(iOS 11.0, *) {
            safeAreaBottomInset = UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0
        }
        
        let height = min(keyboardSize.width, keyboardSize.height)
        let centerY = screenHeight - height/2 - toolbarHeight/2 - safeAreaBottomInset
        self.toolbar.center = CGPoint(x: UIScreen.main.bounds.size.width/2, y: centerY)
        self.view.addSubview(self.toolbar)
    }
}

@objc func keyboardWillHide(_ notification: Notification) {
    self.toolbar.removeFromSuperview()
}

然后,在 viewDidLoad() 函数中,将以下内容添加到您的代码中:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)

这段代码将使我们的 ViewController 监听键盘出现和消失的通知,并分别调用 keyboardWillShow() 和 keyboardWillHide() 函数。

最后,在 keyboardWillShow() 函数中,我们将添加以下内容:

textField.inputAccessoryView = toolbar

这会将我们的 UIToolBar 添加到键盘的文本字段或文本视图中。

完整代码

最终的代码将类似于以下内容:

import UIKit

class ViewController: UIViewController {

    let toolbar = UIToolbar()

    @IBOutlet weak var textField: UITextField!
   
    override func viewDidLoad() {
        super.viewDidLoad()
        
        toolbar.sizeToFit()
        let doneButton = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(doneButtonTapped))
        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        toolbar.items = [flexibleSpace, doneButton]
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    @objc func keyboardWillShow(_ notification: Notification) {
        if let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect {
            let keyboardSize = keyboardFrame.size
            let screenHeight = UIScreen.main.bounds.size.height
            let toolbarHeight = self.toolbar.frame.size.height
            
            var safeAreaBottomInset: CGFloat = 0
            
            if #available(iOS 11.0, *) {
                safeAreaBottomInset = UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0
            }
            
            let height = min(keyboardSize.width, keyboardSize.height)
            let centerY = screenHeight - height/2 - toolbarHeight/2 - safeAreaBottomInset
            self.toolbar.center = CGPoint(x: UIScreen.main.bounds.size.width/2, y: centerY)
            self.view.addSubview(self.toolbar)
        }
    }
    
    @objc func keyboardWillHide(_ notification: Notification) {
        self.toolbar.removeFromSuperview()
    }
    
    @objc func doneButtonTapped() {
        view.endEditing(true)
    }
}
结论

现在,在您的 iOS 应用程序中,每当用户打开键盘时,将显示一个具有自定义工具栏的键盘,该工具栏包含您希望在应用程序中轻松访问的按钮。