article

Thursday, April 21, 2022

SwiftUI Custom Badge Button

SwiftUI Custom Badge Button

ContentView.swift
 
//
//  ContentView.swift
//  CairocodersDev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {

    @State var count = 0
    @State var show = false
    
    var body: some View {
           
        GeometryReader { geometry in
            VStack {
                if self.show && self.count != 0 {
                    HStack(spacing: 12) {
                        
                        Image(systemName: "suit.heart.fill")
                            .resizable()
                            .frame(width: 20, height: 18)
                            .foregroundColor(.red)
                        
                        Text("\(self.count) Likes")
                    }
                    .padding([.horizontal,.top], 15)
                    .padding(.bottom, 30)
                    .background(Color.white)
                    .clipShape(ArrowShape())
                }
                
                Button(action: {
                    self.count += 1
                    self.show.toggle()
                }) {
                    Image(systemName: !self.show ? "suit.heart" : "suit.heart.fill")
                        .resizable()
                        .frame(width: 20, height: 18)
                        .foregroundColor(.red)
                        .padding()
                        .background(Color.white)
                        .clipShape(Circle())
                }
            }
            .frame(width: geometry.size.width, height: geometry.size.height)
        }
        .background(Color.black.opacity(0.06)).edgesIgnoringSafeArea(.all)
        .animation(.interactiveSpring(response: 0.6, dampingFraction: 1, blendDuration: 1))
        .onTapGesture {
            self.show.toggle()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct ArrowShape : Shape {
    
    func path(in rect: CGRect) -> Path {
        return Path{path in
            path.move(to: CGPoint(x: 0, y: 0))
            path.addLine(to: CGPoint(x: rect.width, y: 0))
            path.addLine(to: CGPoint(x: rect.width, y: rect.height - 10))
            
            path.addLine(to: CGPoint(x: (rect.width / 2) - 10, y: rect.height - 10))
            path.addLine(to: CGPoint(x: (rect.width / 2), y: rect.height))
            path.addLine(to: CGPoint(x: (rect.width / 2) + 10, y: rect.height - 10))
            
            path.addLine(to: CGPoint(x: 0, y: rect.height - 10))
        }
    }
}

Related Post