簡體   English   中英

SwiftUI - 根據條件添加導航欄按鈕

[英]SwiftUI - Add a Navigation Bar Button on Condition

鑒於我有這樣的看法..

@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")
            
 }

這會產生一個這樣的視圖,這是預期的:

在此處輸入圖片說明

在我可以使用的欄中添加導航按鈕

 .navigationBarItems(trailing:
  Button(action: {print("Button was tapped")}) {
   Image(systemName: "plus")
    .resizable().frame(width: 20, height: 20)
  })

預期添加按鈕

有沒有辦法只根據條件添加(或顯示)按鈕?

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)
  }
}

如果您不想使用AnyView ,您也可以使用GroupOpacity

.navigationBarItems(trailing: Group {
  if self.tabIndex == 1 {
    Button(action: {print("Button was tapped")}) {
     Image(systemName: "plus")
      .resizable().frame(width: 20, height: 20)
    }
  }
})
.navigationBarItems(trailing: 
    Button(action: {print("Button was tapped")}) {
     Image(systemName: "plus")
      .resizable().frame(width: 20, height: 20)
    }.opacity(self.tabIndex == 1 ? 1 : 0)
)

我知道這個問題有一個公認的答案,我在自己的解決方案中使用了它,但這是我所做的:

var doneButton:AnyView {
    if !fromPreferences {
        return AnyView(Button(action: self.doneAction) {
            Text("Done")
        })
    }
    return AnyView(EmptyView())
}

以及我如何在體內使用它:

.navigationBarItems(trailing: doneButton)

感謝@Asperi 的解決方案!

這是對我有用的方法,即使我的條件為 false 導致沒有返回任何內容(欄項目沒有正確顯示,沒有錯誤)。 我發現它比在三元運算符中壓縮要干凈一些。

.navigationBarItems(
    trailing: Button(
        action: {
            print("My Action")
        }
    ) {
        if myBool {
            Text("My Button")
        }
    }
)

由於.navigationBarItems將在 iOS 的未來版本中棄用,因此最好使用.toolbar(_:)視圖修飾符。

.toolbar {
    ToolbarItemGroup(placement: .navigationBarTrailing) {
        if tabIndex == 2 {
            // show button
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM