首页 > 解决方案 > Swift 中键盘上方的自定义按钮

问题描述

我想知道一些应用程序如何在 iOS 应用程序的键盘上方无缝集成自定义按钮。您可以创建自定义键盘扩展,但这需要付出很多努力并且需要用户启用键盘。但是,某些应用程序可以在不使用键盘扩展程序的情况下完成相同的操作。如何以最有组织的方式实施?

我能想到的一个例子是应用程序 Juno,它提供标准的英文键盘(无键盘扩展),但带有自定义的按钮工具栏。他们是如何实现这一点的?

是否也有办法在 SwiftUI 中实现这一点?

朱诺键盘

编辑

另一个类似的例子: 语法键盘

标签: swiftswiftui

解决方案


这是一个非常基本的方法来设置一个inputAccessoryViewUITextField被包装UIViewRepresentable在 SwiftUI 中使用的 a:

struct ContentView: View {
    
    @State var text = ""
    
    var body: some View {
        
        VStack {
            Text("My text field:")
            TextFieldWithCustomButtons(text: $text)
                .frame(height: 60)
                .border(Color.red)
            Text(text)
        }
        
    }
}

struct TextFieldWithCustomButtons : UIViewRepresentable {
    @Binding var text: String
    
    func makeUIView(context: Context) -> UITextField {
        let textField =  UITextField()
        textField.delegate = context.coordinator
        let customView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 44))
        customView.backgroundColor = UIColor.red
        
        textField.inputAccessoryView = customView // <--- Here
        
        return textField
    }
    
    func updateUIView(_ uiView: UITextField, context: Context) {
        
    }
    
    func makeCoordinator() -> TextFieldWithCustomButtons.Coordinator {
        Coordinator(parent: self)
    }
    
    class Coordinator: NSObject, UITextFieldDelegate {
        var parent: TextFieldWithCustomButtons
        
        init(parent: TextFieldWithCustomButtons) {
            self.parent = parent
        }
        
        func textFieldDidChangeSelection(_ textField: UITextField) {
            parent.text = textField.text ?? ""
        }
        
    }
}

因为inputAccessoryViewis aUIView并且我没有立即看到访问 a 的简单方法UIViewController,所以似乎没有明显的解决方案可以将 SwiftUI 嵌入到附件视图中。但是,如果有一种方法可以在其中嵌入 a UIHostingController,那么您就可以访问 SwiftUI 的附件视图,而不仅仅是 UIKit。


推荐阅读