UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Menu View Wrapper

Forums > SwiftUI

Hi there, I cannot find a solution to create a wrapper menu view. What I try here is to conform to a protocol to have a list of actions but it seems the actions cannot modify wrapped view state. Hope this can be useful to someone else anyway

struct MenuItem: Identifiable {
    var id: String { title }
    var title: String
    var icon: String
    var action: () -> Void
}
protocol Menu {
     var menuItems: [MenuItem] { get }
}
import SwiftUI
struct ValueView: View, Menu {
    @State private var value = 1
    var body: some View {
        HStack {
            Text("Value: \(value)")
                .font(.title)
            Button("ADD", action: add)
        }
    }
    private func add() {
        print("Value before: \(value)")
        value += 1
        print("Value after: \(value)")
        print(self)
    }
    var menuItems: [MenuItem] {
        [MenuItem(title: "Add", icon: "", action: add)]
    }
}
import SwiftUI
struct MenuView<Content>: View where Content: View & Menu {
    var content: () -> Content
    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content
    }
    var body: some View {
        VStack {
            content()
            ForEach(content().menuItems) { item in
                Button(item.title, action: item.action)
                    .font(.headline)
                    .padding()
            }
            Spacer()
        }
    }
}
import SwiftUI
@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            MenuView {
                ValueView()
            }
        }
    }
}

3      

This is the output when add() is call from a simple button inside the view

Value before: 1
Value after: 2
ValueView(_value: SwiftUI.State<Swift.Int>(_value: 1, _location: Optional(SwiftUI.StoredLocation<Swift.Int>)))

3      

This is the output when add() is call from a button created from a MenuItem

Value before: 1
Value after: 1
ValueView(_value: SwiftUI.State<Swift.Int>(_value: 1, _location: nil))

We you can see that location is nil but I don't know why or the meaning anyway

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.