当我尝试使navigationBarItems
三元以具有各种视图时出现此错误:
“?”中的结果值:'表达式的类型“ some View”和“ 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
}
}
这是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()
}
}
}
答案 0 :(得分:2)
错误是用表达式告诉您的:
condition ? true_result : false_result
true_result
和false_result
都必须具有相同的类型。
有多种方法可以解决此问题,这里有两种:
.navigationBarItems(leading: searchTapped ? AnyView(backButton) : AnyView(ProfileImageBarButton(showMenu: $showMenu)))
或
.navigationBarItems(leading: barItems())
...
func barItems() -> some View {
return Group {
if searchTapped {
backButton
} else {
ProfileImageBarButton(showMenu: $showMenu)
}
}
}
答案 1 :(得分:2)
您还可以使用@ViewBuilder
来允许在其正文中放置不同的视图:
.navigationBarItems(leading: barItems)
@ViewBuilder
var barItems: some View {
if searchTapped {
backButton
} else {
ProfileImageBarButton(showMenu: $showMenu)
}
}