文本字段点击正在取消 SwiftUI 中的导航链接

Rog*_*edo 6 textfield ios swift swiftui swiftui-navigationlink

我在使用 SwiftUI 时遇到文本字段和导航视图/链接的奇怪问题

我所做的就是使用导航链接浏览视图,并且目标视图内有一些文本字段。当我点击其中任何一个时,导航会自动关闭。

当点击文本字段并显示键盘时,如何修复导航链接消失的问题?

var emailLoginButton: some View {
    NavigationLink(destination: LoginView(viewModel: .init(mode: .login, isPushed: $viewModel.authViewPushed)), isActive: $viewModel.authViewPushed) {
        Button(action: { viewModel.authViewPushed = true }) {
            HStack {
                Image(systemName: "envelope")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 20, height: 20)
                    .foregroundColor(.white)
                
                Text("continue_with_email".localized())
                    .padding(.horizontal, 20)
            }
        }
        .padding()
        .frame(maxWidth: .infinity)
        .foregroundColor(.white)
        .background(Capsule().fill(Color.primaryPurple))
        .shadow(color: Color.black.opacity(0.15), radius: 5, x: 5, y: 5)
        .padding(.horizontal)
        .padding(.bottom, 20)
    }
    .isDetailLink(false)
}

// Destination's view textfield which "dismisses" navigationLink
var emailTextField: some View {
    HStack {
        Image(systemName: "envelope")
            .font(.title2)
            .foregroundColor(.primary)
            .frame(width: 35)

        TextField(viewModel.emailPlaceholderText.uppercased(), text: $viewModel.email)
            .autocapitalization(.none)
    }
    .padding()
    .background(Color.white.opacity(viewModel.email == stringEmpty ? 0 : 0.12))
    .cornerRadius(12)
    .padding(.horizontal)
}
Run Code Online (Sandbox Code Playgroud)

Izy*_*sky 2

经过一段时间的研究,我发现 NavigationLink 关闭,因为 viewModel 中的 authViewPushed 参数变为 false。发生这种情况是因为由于firstView 更新而正在重新创建viewModel。我遇到了同样的问题,这是解决方案:

struct MyView: View {
    @StateObject var viewModel = MyViewModel()

    var body : some View {
        
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,MyView 正在更新,但 MyViewModel 保持不变。