3

Developing with SwiftUI I'm finding it difficult to reuse code composing views together. I'll show you a simple example: let's say we have a textfield in our app with a specific UI. Let's call this textfield MyTextField. The UI might be:

enter image description here

Here is the code:

struct MyTextField: View {
    @Binding var text: String
    var label: String

    var body: some View {
        VStack {
            HStack {
                Text(label)
                Spacer()
            }
            TextField("", text: $text) //here we have a simple TextField
            Divider()
        }
        .padding()
    }
}

Now, let's say we want to have another textfield with the same UI, but to use in secure contexts. This textfield is called MySecureTextField. In this case I should use SecureField instead of TextField, but clearly I don't want to create an entire new view this way:

struct MySecureTextField: View {
    @Binding var text: String
    var label: String

    var body: some View {
        VStack {
            HStack {
                Text(label)
                Spacer()
            }
            SecureField("", text: $text) //this time we have a SecureField here
            Divider()
        }
        .padding()
    }
}

How can I design a situation like this? I tried several approaches, but none of them seem the right one:

1 - First attempt To have a sort of container view that takes the actual textfield as a parameter:

struct TextFieldContainer<ActualTextField>: View where ActualTextField: View {
    private let actualTextField: () -> ActualTextField
    var label: String

    init(label: String, @ViewBuilder actualTextField: @escaping () -> ActualTextField) {
        self.label = label
        self.actualTextField = actualTextField
    }

    var body: some View {
        VStack {
            HStack {
                Text(label)
                Spacer()
            }
            actualTextField()
            Divider()
        }
        .padding()
    }
}

I could use TextFieldContainer this way:

struct ContentView: View {
    @State private var text = ""

    var body: some View {
        TextFieldContainer(label: "Label") {
            SecureField("", text: self.$text)
        }
    }
}

I don't like this solution: I don't want to specify the actual textfield, it should be implicit in the view itself (MyTextField or MySecureTextField). And this way I could even inject any kind of view inside the container and not just a textfield.

2 - Second attempt To have a private container and two public views that use the container internally:

private struct TextFieldContainer<ActualTextField>: View where ActualTextField: View {
    //...
    //the same implementation as above
    //...
}

struct MyTextField: View {
    @Binding var text: String //duplicated code (see MySecureTextField)
    let label: String //duplicated code (see MySecureTextField)

    var body: some View {
        TextFieldContainer(label: label) {
            TextField("", text: self.$text)
        }
    }
}

struct MySecureTextField: View {
    @Binding var text: String //duplicated code (see MyTextField)
    let label: String //duplicated code (see MyTextField)

    var body: some View {
        TextFieldContainer(label: label) {
            SecureField("", text: self.$text)
        }
    }
}

and use them this way:

struct ContentView: View {
    @State private var text = ""
    @State private var text2 = ""

    var body: some View {
        VStack {
            MyTextField(text: $text, label: "Label")
            MySecureTextField(text: $text2, label: "Secure textfield")
        }
    }
}

I don't really dislike this solution, but there is some code duplication on the properties. If there were a lot of properties there would be a lot of code duplication. Also, if I changed some properties on TextFieldContainer I should change all the views consequently, it may be a lot of structs to change (MyTextField, MySecureTextField, MyEmailTextField, MyBlaBlaTextField, and so forth).

3 - My last attempt Use the same approach as in the second attempt here above, but using AnyView this way:

struct MySecureTextField: View {
    private let content: AnyView

    init(text: Binding<String>, label: String) {
        content = AnyView(TextFieldContainer(label: label) {
            SecureField("", text: text)
        })
    }

    var body: some View {
        content
    }
}

struct MyTextField: View {
    private let content: AnyView

    init(text: Binding<String>, label: String) {
        content = AnyView(TextFieldContainer(label: label) {
            TextField("", text: text)
        })
    }

    var body: some View {
        content
    }
}

It's not that different from the second try and my gut feeling is that I'm missing the right way (the SwiftUI-y way) to do this common task. Can you point me to the right "design pattern" or maybe improve one of the solutions I described? Sorry for the long question.

0

2 Answers 2

13

You can use a simple if!

struct MyTextField: View {
    @Binding var text: String
    var label: String
    var secure: Bool = false

    var body: some View {
        VStack {
            HStack {
                Text(label)
                Spacer()
            }

            if secure {
                SecureField("", text: $text)
            } else {
                TextField("", text: $text)
            }

            Divider()
        }
        .padding()
    }
}

Usage:

MyTextField(text: $text, label: "Label") // unsecure
MyTextField(text: $text, label: "Label", secure: true) // secure
3
  • Thanks Quinn, I upvoted your answer cause this is a simple and clean approach that may be worth it in some simple cases. Commented Sep 26, 2019 at 8:49
  • Just a suggestion: convention is to leave out parentheses when writing swift & explicitly use self only when needed. You can use if secure { in your body if you'd like.
    – ethoooo
    Commented Oct 11, 2019 at 15:36
  • 1
    @ethoooo yes you're right, i jump between kotlin and swift so much that i just always have a habit of putting the parentheses... Ill make a small edit to my answer to keep it pretty
    – Quinn
    Commented Oct 11, 2019 at 15:42
5

Your first attempt is the correct approach, but instead of letting the caller provide the text field, add static methods for the different field types:

struct TextFieldContainer<FieldView>: View where FieldView: View {

    var label: String

    var body: some View {
        VStack {
            HStack {
                Text(label)
                Spacer()
            }
            fieldView
            Divider()
        }
        .padding()
    }

    fileprivate init(label: String, fieldView: FieldView) {
        self.label = label
        self.fieldView = fieldView
    }

    private let fieldView: FieldView
}

extension TextFieldContainer where FieldView == TextField<Text> {
    static func plain(label: String, text: Binding<String>) -> some View {
        return Self(label: label, fieldView: TextField("", text: text))
    }
}

extension TextFieldContainer where FieldView == SecureField<Text> {
    static func secure(label: String, text: Binding<String>) -> some View {
        return Self(label: label, fieldView: SecureField("", text: text))
    }
}

Example use:

struct ContentView: View {
    @State private var text = ""

    var body: some View {
        VStack {
            TextFieldContainer.plain(label: "Label", text: $text)
            TextFieldContainer.secure(label: "Label", text: $text)
        }
    }
}
2
  • Thanks Rob, this is exactly the generic solution I was looking for. Commented Sep 26, 2019 at 8:49
  • Hi Rob, sorry to bother you again: do you know why copy-pasting your code here above the preview doesn't work anymore? If I use the textfield you created in another view there's no problem (the preview works), but the preview of the textfield itself (in the file where the textfield is coded) gives an error: replaced function 'secure(label:text:)' of type '<τ_0_0 where τ_0_0 == SecureField<Text>> (BBTextField<SecureField<Text>>.Type) -> (String, Binding<String>) -> some View' could not be found. Thanks. Commented Sep 26, 2019 at 10:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.