UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Change Background Color When Rendered Button Is Tapped.

Forums > SwiftUI

Alright, the title makes it sound pretty simple, but the problem I'm facing is that I'm rendering a list of buttons from one view file in another. I'm trying to create some type of ternary or conditional modifier so when a user taps one of the rendered buttons, the background color of only that button will toggle green, when they tap it again it returns to its previous color.

My HomeView is the main view where the loop runs and pulls the UI from ContactCardView. ContactCardView has the details on how the information should display, including the default background coloring. What I cannot make sense of is where the conditional logic to change the background color should live. I've tried a few things with no success (@State variables in different places, ternary on the background color modifier).

HomeView - The issue is mainly in the ScrollView at the bottom. The ForEach renders the device contacts using the ContactCardView UI.

struct HomeView: View {
    @StateObject var contactsVM = ContactsViewModel()

    @State private var isEditing = false

    @State private var contactSelected = false

    var body: some View {

        VStack {
            Text("Select your contacts")
                .font(.title2)
                .fontWeight(.semibold)
                .foregroundColor(.white)
                .cornerRadius(10)
                .padding()

            if contactSelected {

                Text("\(contactsVM.selectedContacts.count) Contacts Selected")
                    .font(.title2)
                    .fontWeight(.semibold)
                    .foregroundColor(.white)
                    .cornerRadius(10)
                    .padding()
                    .overlay(
                        RoundedRectangle(cornerRadius: 10)
                            .stroke(Color(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)), lineWidth: 1)
                    )
                Button(action: {

                }) {
                    Text("")
                }
                .padding()

        }

            HStack {
                TextField("Search", text: $contactsVM.filteredText)
                    .padding(6)
                    .padding(.horizontal, 25)
                    .background(Color(.systemGray6))
                    .cornerRadius(8)
                    .padding(.horizontal, 10)
                    .onTapGesture {
                        self.isEditing = true

                    }
                if isEditing {

                    Button(action: {
                        self.isEditing = false
                        self.contactsVM.filteredText = ""

                    }) {
                        Text("Cancel")
                    }
                    .padding(.trailing, 10)
                    .foregroundColor(.white)
                    .transition(.move(edge: .trailing))
                    .animation(.default)
                }
            }
            .padding()

            ScrollView {
                LazyVStack {
                        ForEach(contactsVM.contacts) { contact in
                            ContactCardView(
                                firstName: contact.firstName,
                                lastName: contact.lastName ,
                                phoneNumber: contact.phone ?? "No Info Provided",
                                callback: {
                                    contactsVM.selectedContacts.insert(contact)
                                    contactSelected = true

                                }
                            )
                        }
                }
            }

        }
    }
}

ContactCardView - This is the UI being rendered in HomeView.

struct ContactCardView: View {

    @State var contactSelectedModifier = false

    let firstName: String
    let lastName: String
    let phoneNumber: String
    let callback: () -> Void

    var body: some View {
        VStack {
            Button(action: callback, label: {
                HStack {
                    VStack(alignment: .leading) {
                        Text("\(firstName)")
                            .font(.headline)
                            .foregroundColor(.white)
                        Text("\(lastName)")
                            .font(.title2)
                            .fontWeight(.black)
                            .foregroundColor(.white)
                        Text("\(phoneNumber)".uppercased())
                            .font(.caption)
                            .foregroundColor(.white)
                    }
                }
                .frame(maxWidth: .infinity, alignment: .leading)

                Spacer()

            })
            .padding(5)
            .background(contactSelectedModifier ? Color(#colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)) : Color(#colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)))
            .cornerRadius(10)
            .overlay(
                RoundedRectangle(cornerRadius: 8)
                    .stroke(Color(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)), lineWidth: 1)
            )
        }
    }
}

2      

No sure if this is what you were after. I used blue in the example code below.

HStack {
    TextField("Search", text: $contactsVM.filteredText)
         .padding(6)
         .padding(.horizontal, 25)
         .background(isEditing ? Color.blue : Color(.systemGray6))
         .cornerRadius(8)
         .padding(.horizontal, 10)
         .onTapGesture {
             self.isEditing = true
         }

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.