3

I have a view which sometimes is used to browse data and sometimes to select data.

When used to browse, it is presented by a NavigationLink.

When used to select data, it is presented as a modal sheet and closed by setting binding boolean isPresented to false, so I can make use of sheet function onDismiss.

On browse mode, however, I need a way to skip initializing isPresented binding boolean. The right way would be an optional argument on view init() but all what I try throws an error.

This is the way I call it for browsing data:

NavigationLink(destination:BrowseOrSelectView(selMode:SelModes.browse)) {
Text("Browse")
}

This is the way I call it to select data:

.Sheet(isPresented: self.$isPresented, onDismiss:{...}) {
    BrowseOrSelectView(selMode: SelModes.selection, isPresented: self.$isPresented)
}

This is the view:

struct BrowseOrSelectView: View {
    @State var selMode:SelModes
    @Binding var isPresented:Bool

    public init(selMode: SelModes, isPresented:(Binding<Bool>)? = true) {
        UITableView.appearance().separatorStyle = .none
        _selMode = State(initialValue: selMode)
    }
...
}

The error thrown is:

Cannot convert value of type 'Bool' to expected argument type Binding Bool

1 Answer 1

4

Use .constant binding, like

public init(selMode: String, isPresented:(Binding<Bool>) = .constant(true)) {
    UITableView.appearance().separatorStyle = .none
    _selMode = State(initialValue: selMode)
    _isPresented = isPresented
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great asnswer Asperi, it works!. I should also append an argument with a binding object to keep track of the optional selected value, and the argument should also be optional, since on browse mode it won't be used. What would you use as default value on an argument like , selectedValue:(Binding<CustomObject?>)?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.