我有一个视图,我想将其放入我的公共包中。
此 MyTextField 设计用于:
struct ContentView2: View {
enum Field: Hashable, CaseIterable {
case name
case fullName
case age
}
@FocusState private var focusedField: Field?
.....
我的文本字段:
struct MyTextField: View {
@Binding var text: String
let systemName: String = ""
let focusedValue: ContentView2.Field
var focusedField: FocusState<ContentView2.Field?>.Binding
init(text: Binding<String>, systemName: String, focusedField: FocusState<ContentView2.Field?>.Binding, focusedValue: ContentView2.Field) {
self._text = text
self.focusedField = focusedField
self.focusedValue = focusedValue
}
var body: some View {
HStack {
Image(systemName: systemName)
TextField("Name", text: $text)
.focused(focusedField, equals: focusedValue)
.textFieldStyle(.roundedBorder)
}
}
}
如果我尝试将通用 Hashable 作为输入,来自
var focusedField: FocusState<ContentView2.Field?>.Binding
至 var focusedField: FocusState<Hashable>.Binding
我收到错误
Protocol 'Hashable' as a type cannot conform to the protocol itself
这可能有帮助
struct MyTextField<value: Hashable>: View {
var focusedField: (binding: FocusState<value?>.Binding, equals: value?)
var body: some View {
HStack {
Image(systemName: systemName)
TextField("Name", text: $text)
.focused(focusedField.binding,
equals: focusedValue.equals)
.textFieldStyle(.roundedBorder)
}
}
}
有点晚了,但我会把这个放在这里,供前来寻求的人
import SwiftUI
struct CustomTextField<V: Hashable>: View {
// MARK: - PROPERTIES
@Binding var text: String
@FocusState.Binding var focused: V?
var equals: V
// MARK: - BODY
var body: some View {
TextField("placeholder", text: $text)
.focused($focused, equals: equals)
.textFieldStyle(.roundedBorder)
.padding()
}
}