可以使用 inputAccessoryView 在 UIKit 中的键盘上方创建一个工具栏。但对于 SwiftUI 如何做到这一点呢?因为,SwiftUI 不支持 inputAccessoryView (基于我在网上查找的内容)。我对 UIKit 和 Objective-C 的了解有限,所以不知道如何将 SwiftUI 和 UIKit 结合起来
\nimport SwiftUI\nimport Combine\n\nstruct TipsView: View {\n @State private var amount = ""\n \n var body: some View {\n NavigationView {\n Form {\n Section (header: Text("Amount")) {\n HStack (spacing: 1) {\n if !amount.isEmpty {\n Text("\xc2\xa3")\n }\n TextField("Amount", text: $amount)\n .keyboardType(.decimalPad)\n .onReceive(Just(amount)) { newValue in\n let filtered = newValue.filter { "0123456789.".contains($0)}\n if filtered != newValue {\n amount = filtered\n }\n }\n }//HStack\n }//Section\n }//Form\n }//NavigationView\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n
您可以将 a 包裹UITextField在 a 中UIViewRepresentable,然后将工具栏添加到UITextField.
例如
struct WrappedTextField: UIViewRepresentable {
// binding...
typealias UIViewType = UITextField
func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
textField.delegate = context.coordinator
textField.addDoneButtonOnKeyboard()
return textField
}
func updateUIView(_ uiView: UITextField, context: Context) {
// update binding...
}
func makeCoordinator() -> Coordinator {
return Coordinator()
}
public class Coordinator: NSObject, UITextFieldDelegate {
// delegate methods...
}
}
extension UITextField {
func addDoneButtonOnKeyboard(){
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
doneToolbar.barStyle = .default
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))
let items = [flexSpace, done]
doneToolbar.items = items
doneToolbar.sizeToFit()
self.inputAccessoryView = doneToolbar
}
@objc func doneButtonAction(){
self.resignFirstResponder()
}
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以像普通的 SwiftUI 视图一样使用它
var body: some View {
WrappedTextField(...)
}
Run Code Online (Sandbox Code Playgroud)
要查看如何创建的示例,请在此处UIViewRepresentable查看我的存储库
| 归档时间: |
|
| 查看次数: |
1801 次 |
| 最近记录: |