Search code examples
popoverswiftuixcplayground

Select SwiftUI cell in Popover


I am trying to make a popover in SwiftUI using a UIHostingController with a list that can be tapped. First, the user name and password should be filled in, and then the user role should be tapped in the list, and the popover should be dismissed when the save button is tapped.

Also, the save button in the navigation bar should be disabled until the user information has been verified.

The Xcode playground for this can be fetched from my GitHub repository https://github.com/imyrvold/Popover

To be able to use the AddUserView as a rootView in UIHostingController, I had to use an Xcode storyboard, and add it to the Resources in the Xcode Playground.

import SwiftUI
import Combine

public struct AddUserView : View {
    @ObjectBinding public var loginInfo: LoginInfo
    @EnvironmentObject var viewModel: RoleViewModel
    @State var selectedRole: Role? = nil
    @Environment(\.isPresented) var isPresented: Binding<Bool>?

    public var body: some View {
        NavigationView {
            VStack {
                TextField(self.$loginInfo.firstName, placeholder: Text("First Name"))
                TextField(self.$loginInfo.lastName, placeholder: Text("Last Name"))
                TextField(self.$loginInfo.email, placeholder: Text("Email"))
                SecureField(self.$loginInfo.password, placeholder: Text("Password"))

                Divider()

                List(self.viewModel.roles) { role in
                    RoleCell(role: role).tapAction {
                        self.selectedRole = role
                    }
                }
            }
                .padding()
                .navigationBarTitle(Text("Add User"))
                .navigationBarItems(trailing:
                    Button(action: {
                        self.saveAction()
                        self.isPresented?.value = false
                    }) {
                        Text("Save")
                })//.disabled(!self.loginInfo.isValid)
        }
    }

    // MARK:- Action methods
    func saveAction() {

    }

}

The first problem I have is that when I uncomment the disabled(!self.loginInfo.isValid), all the TextField's are also disabled. Not sure if that is a bug in SwiftUI?

I also want to have the rolecell set the checkmark on the cell when tapped, but so far I have been unable to figure out how to do that.

And how can I dismiss the Popover when the save button is tapped?

Popover Xcode Playground

(When running the playground, have to click the start playground a second time to run properly, the first time the Save popover doesn't work).


Solution

  • Have you tried this

    .navigationBarItems(trailing:
                    Button(action: {
                        self.saveAction()
                        self.isPresented?.value = false
                    }) {
                        Text("Save")
                }.disabled(!self.loginInfo.isValid))