如何在swiftui中添加条件路由

h43kikqp  于 2023-02-21  发布在  Swift
关注(0)|答案(1)|浏览(129)

我在建一个考勤系统。
当我单击搜索按钮时,我想根据视图模型中的if条件导航到另一个屏幕
//查看

Button("Search"){
            loginVM.fetchUser(cId: civil_id, eId: emp_id)
        }

//查看模型

func fetchUser(cId: String?, eId: Int?) {
        let apiService = RegisterDataSource()
        
        apiService.searchEmployee2(civilId: cId, employeeId: eId) { (result: Result<ResultContent?, APIError>) in
            switch result {
            case .success(let user):
                DispatchQueue.main.async {
                    self.resultContent = user
                }
                guard let regStatusID = self.resultContent?.regStatusID else{ return }
                
                // Employee Found
                if(Vontime().key == nil || Vontime().key == ""){
                    // Local Data Not Founded
                    if(regStatusID == 0 || regStatusID == 1){
                        
                        //MARK: Go To Employee Validation Screen
                        
                    } else if (regStatusID == 2){
                        var style = ToastStyle()
                        style.backgroundColor = UIColor.gray.withAlphaComponent(0.6)
                        style.textColor = UIColor.white
                        ToastManager.showToast("employee_waiting", duration: ToastManager.LENGHT_LONG, position: .bottom, style: style)
                    } 
                }

我想我需要创建一条路线,有人能帮忙吗?

nbysray5

nbysray51#

您可以在ViewModel中拥有@Published变量,并通过更新该变量来执行导航。

class MyViewModel: ObservableObject {
@Published var navigateToEmployeeValidationScreenActive = false

func fetchUser(cId: String?, eId: Int?) {
    .
    .
    .
    if(regStatusID == 0 || regStatusID == 1){
        navigateToEmployeeValidationScreenActive = true
        return
    }
    .
    .
    .
  }
}

struct ContentView: View {

@StateObject viewModel: MyViewModel

var body: some View {
    Vstack {
        
        Text("Some Texts")
        
        if viewModel.navigateToEmployeeValidationScreenActive {
            NavigationLink(
                destination: EmployeeValidationView()
            ),
            isActive: $navigateToEmployeeValidationScreenActive,
            label: {
                EmptyView()
            }
            .hidden()
        }
    }
    
  }
}

希望能有所帮助。

相关问题