自定义togglestyle

2021-10-09  本文已影响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

上一篇 下一篇

猜你喜欢

热点阅读