Reputation: 29
I am trying to change the color of a button when it gets selected. Nothing changes when I press the button. Seems like .onTapGesture does not work with a custom view.
I tried to use Buttons instead of .onTapGesture and it didn't work also. .contentShape doesn't work. I also tried to use a List and it works just fine. But I think there is a better way.
import SwiftUI
struct UserSettings: View {
@State private var selectedIndex: Int = 0
var body: some View {
VStack {
HStack(spacing: 0) {
ForEach(0..<3) { subIndex in
let pat = customPatterns1[subIndex]
PatternOptionView(pat: pat, isSelected: subIndex == selectedIndex)
.contentShape(Rectangle())
.onTapGesture(perform: {
selectedIndex = subIndex
})
}
}
}
}
}
struct UserSettings_Previews: PreviewProvider {
static var previews: some View {
UserSettings()
}
}
My Custom View:
import SwiftUI
struct PatternOptionView: View {
var pat: PatternView
var isSelected: Bool
var body: some View {
Button(action: {
Settings.shared.pattern = pat.pattern
}) {
VStack{
Rectangle()
.fill(isSelected ? Color("Primary") : .white)
.frame(width: UIScreen.main.bounds.width / 3, height: UIScreen.main.bounds.width / 3)
.cornerRadius(15)
.contentShape(Rectangle())
.overlay(
Image(systemName: pat.image)
.font(.system(size: 28))
.foregroundColor(isSelected ? .white : Color("Primary"))
)
Text(pat.text)
.foregroundColor(.secondary)
.lineLimit(1)
}
//.padding()
}.contentShape(Rectangle())
}
}
struct PatternOptionView_Previews: PreviewProvider {
static var previews: some View {
PatternOptionView(pat: customPatterns1[0], isSelected: true)
}
}
Upvotes: 2
Views: 1761
Reputation: 209
In my case, I was able to make it work by setting contentShape
:
PatternOptionView(pat: pat, isSelected: subIndex == selectedIndex)
.contentShape(Rectangle())
.onTapGesture(perform: {
selectedIndex = subIndex
})
Upvotes: 6