我希望能够在多个地方使用我的自定义按钮。现在它只能在点击时导航到StartWithPhoneView。当我在其他地方使用时,我也想导航到另一个视图。我可以通过创建两个自定义按钮来实现,但这是代码重复。
struct CustomButtonView: View {
@State var isTapped: Bool = false
var text = ""
var body: some View {
Button(action: {
print("Create account tapped")
self.isTapped.toggle()
}, label: {
RoundedRectangle(cornerRadius: 5)
.frame(width: UIScreen.main.bounds.width / 1.205, height: 44)
.foregroundColor(.blue)
.overlay(Text(text))
.foregroundColor(.white)
})
.padding(.top,15)
NavigationLink("", destination: StartWithPhoneView(), isActive: $isTapped)
}
}
我在这个SignUpView中使用自定义按钮
struct SignupView: View {
var body: some View {
NavigationView {
VStack {
CustomButtonView(text: "Create an account" )
}
NavigationLink("", destination: StartWithPhoneView(), isActive: CustomButtonView.$isTapped) // I want to reach inside CustomButtonView to fetch isTapped
}
}
}
您可以使用Generic
type,这是一个视图
struct CustomButtonView<Destination: View>: View { //<-here
@State var isTapped: Bool = false
var destination: Destination //<- here
var text = ""
var body: some View {
Button(action: {
print("Create account tapped")
self.isTapped.toggle()
}, label: {
RoundedRectangle(cornerRadius: 5)
.frame(width: UIScreen.main.bounds.width / 1.205, height: 44)
.foregroundColor(.blue)
.overlay(Text(text))
.foregroundColor(.white)
})
.padding(.top,15)
NavigationLink("bbbbb", destination: destination, isActive: $isTapped) //<- here
}
}