I created a control which group a TextField, a Text as the label of the TextField, and eventually a Text to signal an error
The result will be something like that:
To declare this control, I write the following Code:
struct TextFieldWithError<T: Hashable>: View {
var label: String
@Binding var text: String
@Binding var textError: String
var focusId: T?
@FocusState.Binding var focus: T?
var body: some View {
VStack {
HStack {
if layout == .hstack {
Text(label)
}
if let focusId {
TextField(label, text: $text)
.focused($focus, equals: focusId)
} else {
TextField(label, text: $text)
.modifier(TextFieldStyle())
}
}
if textError != "" {
Spacer()
.frame(height:2)
HStack {
Text(textError)
.foregroundColor(.red)
.frame(height: textError == "" ? 0 : 20)
.animation(.default)
}
}
}
}
}
if I use a generic for my control, it's because I want to control focus with the .focused modifier and I didn't found another way to do this
now, I want to control the width of the label with a modifier. I thought about writing
.TextFieldWithErrorFrame(labelWidth: <some CGFloatvalue>)
struct TextFieldWithErrorFrame: ViewModifier {
varlabelWidth: CGFloat
func body(content: Content) -> some View {
content
}
}
I think that in place of writing content in the body of my modifier, I have to write the same code that I wrote for the control body, applying a frame modifier on the Label.
But I don't find the way of doing this.
if I declare the modifier as this:
struct TextFieldWithErrorFrame<T>: ViewModifier where T: Hashable {
var width: CGFloat
func body(content: TextFieldWithError<T>) -> some View {
content
}
}
I need to declare an type alias for the body, because I have the error: Type 'TextFieldWithErrorFrame<T>' does not conform to protocol 'ViewModifier'
if I use
typealias Body = TextFieldWithErrorFrame<T>
I have the same error and that's not all. how to rewrite the content in the body of the modifier?