xcodeswiftuiuibuttononappear

xcode swiftui button how to press it programmatically (assign an ID to it ?)


I have a working barcode scanner app (i followed this tutorial https://www.youtube.com/watch?v=44APgBnapag), the only thing Is missing for me if to start the barcode scanner at load instead of the user pressing the button

var body: some View {
        
        NavigationView {
            
            .navigationBarItems (
                trailing:
                Button(action: { self.isPresented.toggle() } ) {
                    Image(systemName: "barcode")
                        .font(Font.system(size: 96))
                }.sheet(isPresented: $isPresented) {
                    BarCodeScanner(isbn: $isbn, foundBooks: $foundBooks)
                }   .padding(.top,42)
            )
            
        }
            
    }

I tried to add a .onAppear

.onAppear {
            print("begin")
            BarCodeScanner(isbn: $isbn, foundBooks: $foundBooks)
        }

but Xcode says Result of 'BarCodeScanner' initializer is unused.

I then wanted to try to press the button programmatically but how to give that button an identifier to make the code press this particular button ?

or is there an other way to make the barcode scanner launch when I open the app ?


Solution

  • You need to set isPresented to True when launching the app:

    ...
        .onAppear {
            isPresented = true
        }
    

    This should work. It will open your barcode scanner as soon as the app launched.