Echo31416
Echo31416

Reputation: 9

Swift not using initialiser when creating a view

I have a specific SwiftUI View that I am using to add and edit variables. When I add the variable, I call the view using this:

Button(action: {
    showingDeviceManager.toggle()
}, label: {
    Text("Add Device")
}) .sheet(isPresented: $showingDeviceManager, content:{
        DeviceEditorView(onScreen: $showingDeviceManager)
    })

And the device editor has this initialiser:

init(){
    editMode = false
}

However, to edit the devices, I need to pass in my data type, so I made this new initialiser:

init(editDevice: Device){
    editMode = true
    self.device = editDevice
}

And call it like this:

Button(action: {
    showingDeviceManager.toggle()
}, label: {
    Text("Edit Device")
}).sheet(isPresented: $showingDeviceManager, content:{
        DeviceEditorView(onScreen: $showingDeviceManager, editDevice:device)
     })

However, when I show the value of editMode, it still shows false. Both of the buttons are outside of the view that is being called.

EDIT: Cut down on extraneous code

Upvotes: 0

Views: 82

Answers (2)

Damien
Damien

Reputation: 3362

I believe you're not using the init you wrote. If the device property is Binding, you should write you want a Binding value in your custom init:

init(editDevice: Binding<Device>){
    editMode = true
    self._device = editDevice
}

Upvotes: 0

malhal
malhal

Reputation: 30726

You don’t normally need custom inits for View structs.

In this situation it’s best to use sheet(item:) where item is the data type you want to edit.

Upvotes: 0

Related Questions