美文网首页
自定义togglestyle

自定义togglestyle

作者: 王勋才 | 来源:发表于2021-10-09 22:11 被阅读0次
    IMG_0333.jpg
    //自定义togglestyle
    import SwiftUI
    
    struct ContentView: View {
        @State private var flag = true
    
        var body: some View {
            VStack(spacing: 10) {
              
                
                Toggle(isOn: $flag) {
                    Text(flag ? "开":"关")
                }.toggleStyle(MyToggleStyle())
            }
        }
    }
    
    struct MyToggleStyle: ToggleStyle {
        func makeBody(configuration: Self.Configuration) -> some View {
            MyToggleView(configuration: configuration)
        }
        
        struct MyToggleView: View {
            let configuration: MyToggleStyle.Configuration
            
            var body: some View {
                HStack {
                    configuration.label
                        .font(.largeTitle)
                    
                    MyToggleSwitch(c: configuration)
                }
            }
        }
        
        struct MyToggleSwitch: View {
            let c: MyToggleStyle.Configuration
    
            var body: some View {
                ZStack(alignment: c.isOn ? .leading : .trailing) {
                    
                    Capsule()
                         .frame(width: 126, height: 50)
                     .foregroundColor(c.isOn ? .green : .gray)
                     .shadow(radius: 2)
                    
                 
                 ZStack {
                         Circle()
                         .fill(c.isOn ? Color.orange : Color.black)
                         .frame(width: 50, height: 50)
                          Text(c.isOn ? "已开" : "已关")
                         .foregroundColor(c.isOn ? .white : .gray)
                         .shadow(radius: 2)
                 }
                 
             }
                .padding(5)
                .background(Color.white)
                .clipShape(Capsule())
                .shadow(radius: 10)
                .onTapGesture {
                    withAnimation {
                        self.c.$isOn.wrappedValue.toggle()
                    }
                        
                }
            }
        }
    }
    
    
    
    

    我的应用简单备忘录上架了。
    https://apps.apple.com/cn/app/%E7%AE%80%E5%8D%95%E5%A4%87%E5%BF%98%E5%BD%95/id1588857931

    相关文章

      网友评论

          本文标题:自定义togglestyle

          本文链接:https://www.haomeiwen.com/subject/kyjcoltx.html