【问题标题】:Custom buttons above Keyboard in SwiftSwift 中键盘上方的自定义按钮
【发布时间】:2021-02-13 15:08:14
【问题描述】:

我想知道一些应用程序如何在 iOS 应用程序的键盘上方无缝集成自定义按钮。您可以创建自定义键盘扩展,但这需要付出很多努力并且需要用户启用键盘。然而,一些应用程序在不使用键盘扩展的情况下也能做到这一点。如何以最有条理的方式实施?

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

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

编辑

另一个类似的例子:

【问题讨论】:

  • 我不相信有办法用直接的 SwiftUI 做到这一点——你可能想看看inputAccessoryView,这可能意味着你将使用 UIViewRepresentable 等处理包装视图。但是,我不会将此作为答案,以防其他人有更好的想法。 PS,你的电池指示灯让我紧张 :) stackoverflow.com/questions/35689528/…
  • 您的目标是 iOS 13 还是 iOS 14?在 iOS 14 中,视图可以避开键盘。

标签: swift swiftui


【解决方案1】:

这是在 UITextField 上设置 inputAccessoryView 的一种非常基本的方法,该 UITextField 已包装在 UIViewRepresentable 中以在 SwiftUI 中使用:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 2020-02-16
    • 2010-12-03
    • 2013-08-06
    相关资源
    最近更新 更多