Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Views with a custom init

Tags:

swift

swiftui

Let's say that I am making a custom input element that looks like this:

struct CustomInput : View {     @Binding var text: String     var name: String      var body: some View {         TextField(name, text: $text)             .modifier(InputModifier())      } } 

Currently, when I instantiate this view I'm required to pass both text and name names to arguments. I want to be able to make the name argument optional, like in the example below.

 CustomInput("Some name", $text) 

Typically I'd use an init method for this. But I'm not sure how to handle property wrappers like @Binding in the init function.

Any ideas on how I can achieve this?

like image 309
bento Avatar asked Jul 06 '19 02:07

bento


People also ask

What does init do in SwiftUI?

Creates a text view that displays a stored string without localization.

How do I init bind a variable in SwiftUI?

In SwiftUI, you can create bindings in 2 ways: With the @Binding property wrapper, which creates a binding, but doesn't store it. With other property wrappers, like @State, which creates a binding, and also stores its value.

How to initialize an object Swift?

An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }

How many types of init in Swift?

Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value. These are known as designated initializers and convenience initializers.


1 Answers

You can write your initializer like this:

struct CustomInput : View {     @Binding var text: String     var name: String      init(_ name: String, _ text: Binding<String>) {         self.name = name          // Beta 3         // self.$text = text          // Beta 4         self._text = text     }      var body: some View {         TextField(name, text: $text)     } } 
like image 142
kontiki Avatar answered Oct 04 '22 19:10

kontiki