当按钮靠近在一起时,SwiftUI NavigationLink 的行为不正确

SwiftUI NavigationLink not behaving correctly when buttons are close together

我正在尝试实现一个可编程的 NavigationLink 以转到另一个视图,由一个简单的按钮触发。但是当那个按钮在另一个按钮旁边时,它不会触发 NavigationLink,而是触发旁边按钮的动作。

struct NavLinkView: View {
    @State var showPasswordStr = true
    @State var showCheckView = false
    @State var password = "Abc"
    var body: some View {
        Form {
            VStack {
                NavigationLink(destination: CheckView(), isActive: $showCheckView ) {
                    EmptyView()
                }
                Text("Password")
                    .font(.system(size: 12, weight: .light, design: .default))
                    .foregroundColor(.gray)
                HStack {
                    
                    if showPasswordStr {
                        TextField("", text: $password)
                            .textFieldStyle(RoundedBorderTextFieldStyle())
                    } else {
                        SecureField("", text: $password)
                            .textFieldStyle(RoundedBorderTextFieldStyle())
                    }
                    Button(action: {
                        showPasswordStr.toggle()
                    } ) {
                        Image(systemName: showPasswordStr ? "eye.slash" : "eye" )
                    }
                    .padding(.leading)

                    Button(action: { showCheckView.toggle() } ) {
                        Image(systemName: "checkmark.circle" )
                    }
                    .padding(.leading)
                }
            }
        }
    }
}

我错过了什么?如果我将 NavigationLink 移动到 VStack 之后,那么两个按钮都会触发第一个按钮和 NavigationLink 的动作。

由于您的按钮位于 Form 中,您需要将其样式更改为 PlainButtonStyle:

Button(action: {
    self.showPasswordStr.toggle()
}) {
    Image(systemName: showPasswordStr ? "eye.slash" : "eye")
}
.buttonStyle(PlainButtonStyle()) // <- add style

Button(action: { self.showCheckView.toggle() }) {
    Image(systemName: "checkmark.circle")
}
.buttonStyle(PlainButtonStyle()) // <- add style