6.6_显示或隐藏表单行

SwiftUI 允许我们可以根据需要在表单中添加和删除项目,当我们希望调整基于先前选项可见的选项列表时,特别有用。

例如,这会显示单个 toggle ,提示用户是否要显示更多高级选项。启用该 toggle 后,会出现第二个 toggle ,允许他们启用日志记录:

struct ContentView : View {
    
    @State var showingAdvancedOptions = false
    @State var enableLogging = false
    
    var body: some View {
        Form {
            Section {
                Toggle(isOn: $showingAdvancedOptions) {
                    Text("Show advanced options")
                }
                
                if showingAdvancedOptions {
                    Toggle(isOn: $enableLogging) {
                        Text("Enable logging")
                    }
                }
            }
        }
    }
}

运行效果: 6.6_form_show_hide 与其他绑定一样,可以要求 SwiftUI 对绑定更改导致的视图更改使用隐式动画,如下所示:

struct ContentView: View {
    
    @State var showingAdvancedOptions = false
    @State var enableLogging = false
    
    var body: some View {
        Form {
            Section {
                Toggle(isOn: $showingAdvancedOptions.animation()) {
                    Text("Showing Advanced Options")
                }
            }
            
            if showingAdvancedOptions {
                Toggle(isOn: $enableLogging) {
                    Text("Enable Logging")
                }
            }
        }
    }
}

运行效果: 6.6_form_show_hide_animation

Avatar
M X
Mobile, Front-End Developer

My research interests include swift developing, python developing and go developing.

Related

Next
Previous
comments powered by Disqus