swift - Swift 中键盘上方的自定义按钮
问题描述
我想知道一些应用程序如何在 iOS 应用程序的键盘上方无缝集成自定义按钮。您可以创建自定义键盘扩展,但这需要付出很多努力并且需要用户启用键盘。但是,某些应用程序可以在不使用键盘扩展程序的情况下完成相同的操作。如何以最有组织的方式实施?
我能想到的一个例子是应用程序 Juno,它提供标准的英文键盘(无键盘扩展),但带有自定义的按钮工具栏。他们是如何实现这一点的?
是否也有办法在 SwiftUI 中实现这一点?
编辑:
解决方案
这是一个非常基本的方法来设置一个inputAccessoryView
已UITextField
被包装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 ?? ""
}
}
}
因为inputAccessoryView
is aUIView
并且我没有立即看到访问 a 的简单方法UIViewController
,所以似乎没有明显的解决方案可以将 SwiftUI 嵌入到附件视图中。但是,如果有一种方法可以在其中嵌入 a UIHostingController
,那么您就可以访问 SwiftUI 的附件视图,而不仅仅是 UIKit。
推荐阅读
- r - 拟南芥基因 ID 转换(BioMart,CLC Genomics Workbench 输出)
- mysql - 如何在 NodeJS 中使用 MySQL@Session 变量?
- javascript - 如何收集选中的单选按钮并放入数组然后发布到控制器
- google-compute-engine - BitBucket 到 Google Compute Engine 代码部署
- java - 有没有更好的方法来处理 Java 中的多个空检查?
- javascript - 如何使用 JS 进行动态引导分页?
- android - RecyclerView 中的项目在重复
- mysql - 将大型 sql 文件(每天 30 gb)导入到 elasticseach 中的单个索引
- bash - Bash:如何检查目录是否存在以及其中是否包含文件
- amazon-web-services - 使用 ansible shell 模块时如何使 aws 命令对 sh 可用?