gpt4 book ai didi

ios - SwiftUI - 根据条件添加导航栏按钮

转载 作者:行者123 更新时间:2023-12-01 15:53:22 29 4
gpt4 key购买 nike

鉴于我有这样的看法..

@State var tabIndex: Int = 0

var body: some View {

TabView(selection: $tabIndex)
{
Text("Tab 1").tabItem({
Image(systemName: "message")
}).tag(0)

Text("Tab 2").tabItem({
Image(systemName: "arkit")
}).tag(1)

Text("Tab 3").tabItem({
Image(systemName: "battery.100")
}).tag(2)
}.navigationBarTitle("Tabbed View")

}
这会产生这样的 View ,这是预期的:
enter image description here
向我可以使用的栏添加导航按钮
 .navigationBarItems(trailing:
Button(action: {print("Button was tapped")}) {
Image(systemName: "plus")
.resizable().frame(width: 20, height: 20)
})
它将按钮添加为 expected
有没有办法只根据条件添加(或显示)按钮?
if (self.tabIndex == 1){
show button
}
else {
don't show button
}

最佳答案

这是可能的方法

.navigationBarItems(trailing: self.tabIndex == 1 ? 
AnyView(self.trailingButton) : AnyView(EmptyView()))

低于 body
var trailingButton: some View {
Button(action: {print("Button was tapped")}) {
Image(systemName: "plus")
.resizable().frame(width: 20, height: 20)
}
}

关于ios - SwiftUI - 根据条件添加导航栏按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59575789/

29 4 0