[英]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
,您也可以使用Group
或Opacity
。
.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.