iOS全局输入附件视图实现:如何为系统键盘添加功能按钮?
Hey there! Let's break down how to build that global math symbol/formula input accessory view you're aiming for—since Apple doesn't offer a native "global input accessory" API, we've got a couple solid workarounds that get the job done:
方案1:用Keyboard Extension打造「类附件」全局键盘
This is the most reliable approach, since Apple’s official global input tool is the Keyboard Extension. Instead of replacing the entire system keyboard, we’ll build a slim, accessory-style keyboard just for your math symbols:
- Design a short-height keyboard (matching the look of an input accessory) filled only with your math formula/symbol buttons
- Let users toggle between the system keyboard and your math panel via the standard keyboard switcher
- When a symbol is tapped, insert it directly into the active input field using the system’s text proxy
Core implementation steps:
- Set a compact height for your keyboard in
InputViewController:override func viewDidLoad() { super.viewDidLoad() // Match the typical input accessory height preferredContentSize = CGSize(width: view.frame.width, height: 60) } - Add tap actions for your symbol buttons to insert text:
@IBAction func insertPi(_ sender: UIButton) { textDocumentProxy.insertText("π") } @IBAction func insertQuadraticFormula(_ sender: UIButton) { textDocumentProxy.insertText("x = (-b ± √(b²-4ac))/(2a)") } - Don’t forget to configure your extension’s
Info.plistto enable full system access and support the text input types you need.
方案2:全局悬浮符号面板(iOS 13+,需权限)
If you want something that sits on top of the system keyboard rather than being a separate keyboard, you can build a floating panel. Note this requires extra permission handling and has some compatibility limits:
- Create a floating view using a custom
UIWindoworUIPointerInteraction - Listen for system notifications like
UITextFieldTextDidBeginEditingNotificationto show/hide the panel when an input field is active - When a symbol is tapped, use
UIApplication.shared.sendAction(_:to:from:for:)or simulate paste to insert the text into the active field
⚠️ Heads up: Users will need to enable "Floating Window" permissions for your app (you’ll have to guide them to Settings), and this might not work smoothly in all apps due to sandbox restrictions.
Quick Notes
- If you only need this for a handful of apps instead of every app, building app-specific input accessory views is simpler (per Apple’s recommendation), but it’s more maintenance work.
- For complex LaTeX-style formulas, you’ll need to convert them to plain text/rendered rich text before inserting—look into third-party math rendering libraries if you need formatted equations.
内容的提问来源于stack exchange,提问作者Milan Nosáľ

