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

标签 ios conditional-statements swiftui

鉴于我有这样的看法..

@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/

相关文章:

ios - UITextField 不会结束 Swift 4 中 UITableViewCell 中的编辑

java - 这个条件意味着什么 if (null == (is = con.getErrorStream()))

swift - 如何使用 swiftUI View 在启动时将 Google map 相机聚焦在用户当前位置

image - SwiftUI 全屏图像背景

ios - 使用静态变量还是通过 View Controller ? iOS

ios - 为什么我的语言包路径在iOS Swift中返回nil?

c# - 条件运算符与 if then else

webview - 如何在 SwiftUI View 中插入 iframe?

iOS 自动使用自定义阿拉伯语/西里尔语字体

PHP - 带括号的简单条件