Home > Back-end >  Youtube like/dislike buttons function in SwiftUI
Youtube like/dislike buttons function in SwiftUI

Time:04-24

Firstly, I am a complete beginner in Swift and SwiftUI.

I am trying to create buttons or toggle feature similar to that of the youtube like/dislike function.

I can create the buttons but I'm struggling with, how to turn button A off when button B is toggled on, and vice versa. whilst also maintaining there individual on/off functionality when clicked. I have seen similar questions being answered but not for SwiftUI

Thanks in advance!

struct ContentView: View{
    @State var isOnGreen = false
    @State var isOnRed = false
    var body: some View {
        
              
            HStack{
                
                VStack {
                    Toggle(isOn: $isOnRed, label: {
                        Image (systemName: "arrowtriangle.down")
                        
                    })
                        .toggleStyle(.button)
                        .tint(.red)
                
                VStack {
                    Toggle(isOn: $isOnGreen, label: {
                        Image (systemName: "arrowtriangle.up")
                    })
                    
                        .toggleStyle(.button)
                        .tint(.green)
                    
                }

CodePudding user response:

Add a modifier to your HStack that monitors for the change in isOnRed or isOnGreen:

var body: some View {
  HStack {
    // ...
  }
  .onChange(of: isOnGreen) { val in
    if val { isOnRed = false }
  }
  .onChange(of: isOnRed) { val in
    if val { isOnGreen = false }
  }
}
  • Related