gpt4 book ai didi

swift - '? :'表达式中的结果值具有不匹配的类型 'some View'和 '...'

转载 作者:行者123 更新时间:2023-12-03 15:21:37 25 4
gpt4 key购买 nike

当我尝试对navigationBarItems进行三元操作以获取各种 View 时,出现此错误:

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
}
}
这是 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()
}
}
}

最佳答案

错误是在表达式中告诉您的:

condition ? true_result : false_result
true_resultfalse_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)
}
}
}

关于swift - '? :'表达式中的结果值具有不匹配的类型 'some View'和 '...',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57343163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com