如何使按钮有条件地隐藏或禁用?



如何切换按钮的存在是否隐藏?
我们有非条件的 .hidden(( 属性; 但我需要条件版本。

注意:我们确实有可用的 .disabled(bool(属性,但没有.hidden(bool(。

struct ContentView: View {
var body: some View {
ZStack {
Color("SkyBlue")
VStack {
Button("Detect") {
self.imageDetectionVM.detect(self.selectedImage)
}
.padding()
.background(Color.orange)
.foreggroundColor(Color.white)
.cornerRadius(10)
.hidden() // ...I want this to be toggled.
}
}
}
}

我希望hidden修饰符稍后得到参数,但从那时起,设置alpha

@State var shouldHide = false
var body: some View {
Button("Button") { self.shouldHide = true }
.opacity(shouldHide ? 0 : 1)
}

对我来说,当你不想看到它时,将frame的高度设置为零是完美的。当您想要计算出大小时,只需将其设置为nil

SomeView
.frame(height: isVisible ? nil : 0)

如果除了隐藏它之外还想禁用它,则可以使用切换的布尔值设置.disabled

SomeView
.frame(height: isVisible ? nil : 0)
.disabled(!isVisible)

这里的所有答案都专门用于有条件地隐藏按钮。

我认为可能会有所帮助的是有条件地制作修饰符本身,例如: .hidden 表示按钮/视图,或者 .italic 表示文本等。

使用扩展。

对于有条件的斜体文本,这很容易,因为 .italic 修饰符返回文本:

extension Text {
func italicConditionally(isItalic: Bool) -> Text {
isItalic ? self.italic() : self
}
}

然后像这样应用条件斜体:

@State private var toggle = false
Text("My Text")
.italicConditionally(isItalic: toggle)

然而,对于按钮来说,这很棘手,因为 .hidden 修饰符返回"一些视图":

extension View {
func hiddenConditionally(isHidden: Bool) -> some View {
isHidden ? AnyView(self.hidden()) : AnyView(self)
}
}

然后像这样应用条件隐藏:

@State private var toggle = false
Button("myButton", action: myAction)
.hiddenConditionally(isHidden: toggle)

你可以利用 SwiftUI 新的双向绑定,并添加一个 if 语句作为:

struct ContentView: View {
@State var shouldHide = false
var body: some View {
ZStack {
Color("SkyBlue")
VStack {
if !self.$shouldHide.wrappedValue { 
Button("Detect") {
self.imageDetectionVM.detect(self.selectedImage)
}
.padding()
.background(Color.orange)
.foregroundColor(Color.white)
.cornerRadius(10)
}
}
}
}
}

这样做比将不透明度设置为 0 的好处是,它将从 UI 中删除奇怪的间距/填充,因为按钮仍在视图中,只是不可见(如果按钮在其他视图组件之间,也就是说(。

您可以使用条件语句轻松地隐藏 SwiftUI 中的视图。

struct TestView: View{

@State private var isVisible = false

var body: some View{

if !isVisible {
HStack{
Button(action: {
isVisible.toggle()
// after click you'r view will be hidden
}){
Text("any view")
}
}
}

}
}

这并不总是一个漂亮的解决方案,但在某些情况下,有条件地添加它也可能有效:

if shouldShowMyButton {
Button(action: {
self.imageDetectionVM.detect(self.selectedImage)
}) {
Text("Button")
}          
}

在没有显示的情况下,会出现空白区域的问题,这可能或多或少是一个问题,具体取决于具体的布局。 可以通过添加一个else语句来解决,该语句或者添加一个大小相等的空格。

@State private var isHidden = true       
VStack / HStack
if isHidden {
Button {
if !loadVideo(),
let urlStr = drill?.videoURL as? String,
let url = URL(string: urlStr) {
player = VideoPlayerView(player: AVPlayer(), videoUrl: url)
playVideo.toggle()
}
} label: {
Image(playVideo ? "ic_close_blue" : "ic_video_attached")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 50)
}
.buttonStyle(BorderlessButtonStyle())
}

.onAppear {
if shouldShowButton {
isHidden = false
} else {
isVideoButtonHidden = true
}
}

相关内容

最新更新