I get this error when I’m trying to ternary the navigationBarItems
to have various views:
Result values in '? :' expression have mismatching types 'some View' and 'ProfileImageBarButton'
@State var searchTapped: Bool = false
var body: some View {
NavigationView {
Text("lol")
--> here i get the error .navigationBarItems(leading: searchTapped ? backButton : ProfileImageBarButton(showMenu: $showMenu))
.navigationBarTitle(Text(""), displayMode: .inline)
}.overlay(searchTextField)
}
private var backButton: some View {
Image(systemName: "arrow.left")
.foregroundColor(Color.blue)
.onTapGesture {
self.searchTapped = false
}
}
This is ProfileImageBarButton
:
struct ProfileImageBarButton: View {
@Binding var showMenu: Bool
var body: some View {
Image(uiImage: UserDefaults.standard.getProfileImage()!)
.resizable()
.renderingMode(.original)
.frame(width: 30, height: 30)
.clipShape(Circle())
.onTapGesture {
self.showMenu.toggle()
}
}
}
The error is telling you that, in an expression:
condition ? true_result : false_result
both true_result
and false_result
need to have the same type.
There are multiple ways to overcome this, here are two:
.navigationBarItems(leading: searchTapped ? AnyView(backButton) : AnyView(ProfileImageBarButton(showMenu: $showMenu)))
or
.navigationBarItems(leading: barItems())
...
func barItems() -> some View {
return Group {
if searchTapped {
backButton
} else {
ProfileImageBarButton(showMenu: $showMenu)
}
}
}
You can also use @ViewBuilder
which allows you to put different views in its body:
.navigationBarItems(leading: barItems)
@ViewBuilder
var barItems: some View {
if searchTapped {
backButton
} else {
ProfileImageBarButton(showMenu: $showMenu)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With