gpt4 book ai didi

swiftui - 如何在键盘上方添加工具栏

转载 作者:行者123 更新时间:2023-12-04 08:55:11 26 4
gpt4 key购买 nike

enter image description here
可以使用 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
}
}

最佳答案

你可以包装一个 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 View 一样使用它
var body: some View {
WrappedTextField(...)
}
查看如何创建的示例 UIViewRepresentable s 结帐我的 repo here

关于swiftui - 如何在键盘上方添加工具栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63862453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com