SwiftUI from entry to actual combat Chapter 2 Section 6: Toggle

Related courses: http://hdjc8.com/hdjc/swiftUI/

Toggle is equivalent to UIToggle in UIKit, which is used to realize the function of option switch (open or close).

Toggle switch controls are very common, such as the option switches for Bluetooth and flight mode on the phone settings page. Mainly used to identify whether to select a certain option, or whether to activate a certain function.


Sample code:

struct ContentView : View {
    //首先添加一个布尔类型的属性,并设置它的初始值为真。该属性拥有@State绑定包装标记,表示该属性将和开关控件进行数据绑定。
    @State var showNotification = true

    var body: some View {
        VStack {
            //然后修改此处的文本视图,作为形状控件的标签。
            Text("Show Notification: ")
            //通过扩展方法,添加另一个文本视图,该文本视图用来显示布尔属性的值。
            + Text("\(self.showNotification.description)")
                .foregroundColor(.green)
                .bold()
                
            //添加一个开关控件,并将它和布尔属性进行绑定。当用户调整开关控件时,该属性的值也将同步发生变化。
            Toggle(isOn: $showNotification) {
                Text("Show notification:")
            }.padding()
        }
    }
}

 

View the results of the operation:

Guess you like

Origin blog.csdn.net/fzhlee/article/details/106101019