有人知道是否可以向自动建议栏添加按钮?最终尝试了下面的代码,我能够在键盘顶部添加一个按钮。但很困惑是否有一个 api 允许我们修改自动更正状态栏。
自定义文本字段
import Foundation
import UIKit
import SwiftUI
struct CustomTextfield: UIViewRepresentable {
@Binding var text: String
var keyType: UIKeyboardType
func makeUIView(context: Context) -> UITextField {
let textfield = UITextField()
textfield.keyboardType = keyType
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textfield.frame.size.width, height: 44))
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(textfield.doneButtonTapped(button:)))
toolBar.items = [doneButton]
toolBar.setItems([doneButton], animated: true)
textfield.leftView = toolBar
return textfield
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text
}
}
extension UITextField{
@objc func doneButtonTapped(button:UIBarButtonItem) -> Void {
self.resignFirstResponder()
}
}
测试视图
import Foundation
import SwiftUI
struct TestView : View {
@State var text = ""
var body: some View {
CustomTextfield(text: $text, keyType: UIKeyboardType.asciiCapable)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 50)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(Color.blue, lineWidth: 4)
)
}
}
这不是我们可以直接做的事情。 建议栏是一个系统组件,没有公共 API 可以对其进行自定义。
您需要创建一些自定义的东西。 您可以将工具栏设置为文本字段的 inputAccessoryView,而不是使用 leftView。这样,它就会出现在键盘正上方,而不会遮挡建议栏。
import Foundation
import UIKit
import SwiftUI
struct CustomTextField: UIViewRepresentable {
@Binding var text: String
var keyType: UIKeyboardType
func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
textField.keyboardType = keyType
textField.borderStyle = .roundedRect
textField.delegate = context.coordinator
// Create the toolbar
let toolBar = UIToolbar()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: context.coordinator, action: #selector(Coordinator.doneButtonTapped))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolBar.items = [flexibleSpace, doneButton]
textField.inputAccessoryView = toolBar // Attach the toolbar to the text field
return textField
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: CustomTextField
init(_ parent: CustomTextField) {
self.parent = parent
}
@objc func doneButtonTapped() {
// Dismiss the keyboard
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
}
使用 inputAccessoryView 放置工具栏(工具栏将显示在键盘上方,而不覆盖建议栏)
在测试视图中:
import Foundation
import SwiftUI
struct TestView: View {
@State private var text = ""
var body: some View {
CustomTextField(text: $text, keyType: .asciiCapable)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 44)
.padding()
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(Color.blue, lineWidth: 4)
)
}
}