可以使用inputAccessoryView在UIKit中的键盘上方创建工具栏。但是,如何为SwiftUI完成呢?由于,SwiftUI不支持inputAccessoryView(基于我在网上查找的内容)。我对UIKit和Objective-C的了解有限,所以不确定如何将SwiftUI和UIKit结合起来
import SwiftUI
import Combine
struct TipsView: View {
@State private var amount = ""
var body: some View {
NavigationView {
Form {
Section (header: Text("Amount")) {
HStack (spacing: 1) {
if !amount.isEmpty {
Text("£")
}
TextField("Amount", text: $amount)
.keyboardType(.decimalPad)
.onReceive(Just(amount)) { newValue in
let filtered = newValue.filter { "0123456789.".contains($0)}
if filtered != newValue {
amount = filtered
}
}
}//HStack
}//Section
}//Form
}//NavigationView
}
}
答案 0 :(得分:2)
您可以将UITextField
包裹在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()
}
}
然后,您将可以像普通的SwiftUI视图一样使用它
var body: some View {
WrappedTextField(...)
}
查看如何创建UIViewRepresentable
的我的仓库here的结帐示例