Selected and unselected from HStack logic - swift

i want that when i pressed on 5th box then all left box will fill , and when i click on eg. 1 then unselected last 4 box , but not 1,
if i clicked on 2nd box then last 3 will be unselected , Thank you in Advanced
#State var SelectedAppsname = [1,2]
ForEach (1..<6){ index in
Button(action: {
let count = selectedAppsName.count
print(count, "count")
print(index,"index")
if selectedAppsName.contains(index) {
print(index, "inINdex")
for i in 0..<count {
if (index<=i) {
}
else {
let new = count - index
print(new, "new")
selectedAppsName.removeLast(new)
}
}
}
else {
for i in count + 1...index {
selectedAppsName.append(i)
}
}
}, label: {
RoundedRectangle(cornerRadius: 16).fill(Color.secondary.opacity(0.5))
.frame(width: 49.4, height: 56, alignment: .center)
})
.background(RoundedRectangle(cornerRadius: 16).fill( selectedAppsName.contains(index) ? Color(red: 1.0, green: 0.9, blue: 0.02) : Color.clear))
}
}

Make it simple:
#State private var level = 0
var body: some View {
HStack {
ForEach(0..<6) { index in
Button {
withAnimation {
level = index
}
} label: {
RoundedRectangle(cornerRadius: 5)
.foregroundColor(index > level ? .gray : .yellow)
.frame(width: 49.4, height: 56, alignment: .center)
}
}
}
}

Related

#State Property not accumulating

Users can swipe left or right on a stack of cards to simulate "true" or "false" to a series of quiz questions. I have a #State var called userScore initialized to 0. When dragGesture .onEnded, I compare the "correctAnswer" with the "userAnswer." If they match, add 1 point to the userScore.
The problem: The console prints 1 or 0. The score does not ACCUMULATE.
Please help me calculate the user's final score? Thanks in advance. . .
import SwiftUI
struct CardView: View {
#State var offset: CGSize = .zero
#State var userScore: Int = 0
#State var userAnswer: Bool = false
private var currentQuestion: Question
private var onRemove: (_ user: Question) -> Void
init(user: Question, onRemove: #escaping (_ user: Question) -> Void) {
self.currentQuestion = user
self.onRemove = onRemove
}
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 25, style: .continuous)
.fill(
Color.black
.opacity(1 - Double(abs(offset.width / 50)))
)
.background(
RoundedRectangle(cornerRadius: 25, style: .continuous)
.fill(offset.width > 0 ? Color.green : Color.red)
//.overlay(offset.width > 0 ? likeGraphics() : dislikeGraphics(), alignment: .topLeading)
)
.shadow(color: .red, radius: 5, x: 0.0, y: 0.0)
VStack {
Image(currentQuestion.imageIcon)
.resizable()
.scaledToFit()
.foregroundColor(Color.white)
.frame(width: 75, height: 75)
ScrollView {
Text(currentQuestion.questionText)
.font(.largeTitle)
.foregroundColor(Color.white)
.multilineTextAlignment(.leading)
}
}
.padding()
}
.frame(width: 300, height: 375) //check: www.ios-resolution.com
.offset(offset)
.rotationEffect(.degrees(offset.width / 400.0 ) * 15, anchor: .bottom)
//.opacity(2 - Double(abs(offset.width / 50.0))) //fade on drag too?
.gesture(
DragGesture()
.onChanged { gesture in
withAnimation(.spring()) {
offset = gesture.translation
}
}
.onEnded { value in
withAnimation(.interactiveSpring()) {
if abs(offset.width) > 100 {
onRemove(currentQuestion)
if (currentQuestion.correctAnswer == determineSwipeStatus()) {
userScore += 1
}
print(userScore)
} else {
offset = .zero
}
}
}
)
}
func determineSwipeStatus() -> Bool {
if(offset.width > 0) {
userAnswer = true
} else if (offset.width < 0) {
userAnswer = false
}
return userAnswer
}
func getAlert() -> Alert {
return Alert(
title: Text("Your group is \(userScore)% cult-like!"),
message: Text("Would you like to test another group?"),
primaryButton: .default(Text("Yes, test another group"),
action: {
//transition back to screen one
//self.showQuizPageScreen.toggle()
}),
secondaryButton: .cancel())
}
}
struct CardView_Previews: PreviewProvider {
static var previews: some View {
CardView(user: Question(id: 1,
imageIcon: "icon1",
questionText: "Dummy placeholder text",
correctAnswer: true),
onRemove: { _ in
//leave blank for preview purposes
})
}
}

iOS | SwiftUI | Undesirable result to exchange items between TimerView and TaskView through ContentView, #State isn't delivering results

I have three Views exchanging information, ContentView, TimerView and TaskView. I used #Binding in TaskView to bring data from TaskView to ContentView, now I want to use that data to pass into TimerView.
I created a #State variable in ContentView to store the data from TaskView, but when I try to use that #State variable to pass data to TimerView it isn't giving me any desirable results.
Now if you see the TasksView call in ContentView, I get the output for the print statement, but in the main TimerView, it doesn't change from the default I set as #State variable in timerInfo.
Any help is appreciated, thank you.
Code for ContentView ->
//
// ContentView.swift
// ProDActivity
//
// Created by Vivek Pattanaik on 5/27/21.
//
import SwiftUI
struct TimerInfo : Identifiable {
let id = UUID()
// let taskIndex : Int
// let taskProjectName : String
var timerTaskName : String
var timerMinutes : Float
let timerIntervals : Int
var timerPriority : String
var timerShortbreakMinute : Float
var timerLongbreakMinute : Float
var timerLongbreakInterval : Int
}
struct ContentView: View {
init() {
UITabBar.appearance().backgroundColor = UIColor.init(Color("TabBar "))
}
// #State var selection: Tab = .dasboard
#State var timerInfo = TimerInfo(timerTaskName: "Sample Task 1", timerMinutes: 30, timerIntervals: 10, timerPriority: "High Priority", timerShortbreakMinute: 5, timerLongbreakMinute: 15, timerLongbreakInterval: 3)
var body: some View {
TabView {
TimerView(defaultTimeRemaining: self.timerInfo.timerMinutes * 60, timeRemaining: self.timerInfo.timerMinutes * 60)
.tabItem {
Image(systemName: "clock.fill")
Text("Timer")
}.tag(0)
TasksView(didClickTimer: { info in
self.timerInfo.timerTaskName = info.timerTaskName
self.timerInfo.timerMinutes = info.timerMinutes
self.timerInfo.timerPriority = info.timerPriority
self.timerInfo.timerShortbreakMinute = info.timerShortbreakMinute
self.timerInfo.timerLongbreakMinute = info.timerLongbreakMinute
self.timerInfo.timerLongbreakInterval = info.timerLongbreakInterval
print("\(self.timerInfo.timerMinutes)ContentView")
})
.tabItem {
Image(systemName: "doc.plaintext.fill")
Text("Tasks")
}.tag(1)
StatisticsView()
.tabItem {
Image(systemName: "chart.pie.fill")
Text("Statistics")
}.tag(3)
SettingsView()
.tabItem {
Image(systemName: "gearshape.fill")
Text("Settings")
}.tag(4)
}
.font(.headline)
.accentColor(Color("AccentColor"))
.environment(\.colorScheme, .dark)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Code for TasksView ->
//
// TasksView.swift
// ProDActivity
//
// Created by Vivek Pattanaik on 5/30/21.
//
import SwiftUI
struct TaskLabels : Identifiable {
let id = UUID()
// let taskIndex : Int
// let taskProjectName : String
let taskName : String
let taskPriority : String
let taskIntervals : String
let taskMinutes : String
let shortBreakMinutes : String
let longBreakMinutes : String
let longBreakIntervals : String
}
struct TaskRow: View {
let tasks : TaskLabels
var body: some View {
HStack(alignment: .center, spacing: 10) {
Image(tasks.taskPriority)
.frame(width: 40, height: 40, alignment: .center)
VStack(alignment: .leading, spacing:4){
Text(tasks.taskName)
.font(.system(size: 15))
Text("\(tasks.shortBreakMinutes) Min Breaks")
.font(.system(size: 13))
}
.frame(width: 100, height: 20, alignment: .leading)
Spacer()
VStack(alignment: .trailing, spacing:4){
Text("0/\(tasks.taskIntervals)")
Text("\(tasks.taskMinutes) Min Tasks")
.font(.system(size: 13))
}
.frame(width: 90, height: 20, alignment: .trailing)
.padding()
}
}
}
struct TasksView: View {
// #Binding var timeSelected : Float
#State var addTasksModalView: Bool = false
#State var taskLabels : [TaskLabels] = []
var didClickTimer : (TimerInfo) -> ()
var body: some View {
NavigationView{
if taskLabels.count != 0 {
List{
ForEach(taskLabels) { task in
HStack {
Button(action: {
self.didClickTimer(.init(timerTaskName: task.taskName, timerMinutes: Float(task.taskMinutes)!, timerIntervals: Int(task.taskIntervals)!, timerPriority: task.taskPriority, timerShortbreakMinute: Float(task.shortBreakMinutes)!, timerLongbreakMinute: Float(task.longBreakMinutes)!, timerLongbreakInterval: Int(task.longBreakIntervals)!))
print(task.taskMinutes)
}, label: {
TaskRow(tasks: task)
})
}
}
.onDelete(perform: self.deleteRow)
}
.navigationBarTitle("Tasks")
.navigationBarItems(trailing: Button(action: {
self.addTasksModalView = true
}, label: {
Image(systemName: "plus.square.on.square")
.resizable()
.frame(width: 26, height: 26, alignment: .leading)
.foregroundColor(Color.accentColor)
}))
.sheet(isPresented: $addTasksModalView, content: {
AddTasks(addTaskPresented: $addTasksModalView) { tasks in
taskLabels.append(tasks)
}
})
} else {
Text("")
.navigationTitle("Tasks")
.navigationBarTitle("Tasks")
.navigationBarItems(trailing: Button(action: {
self.addTasksModalView = true
}, label: {
Image(systemName: "plus.square.on.square")
.resizable()
.frame(width: 26, height: 26, alignment: .leading)
.foregroundColor(Color.accentColor)
}))
.sheet(isPresented: $addTasksModalView, content: {
AddTasks(addTaskPresented: $addTasksModalView) { tasks in
taskLabels.append(tasks)
}
})
}
}
.environment(\.colorScheme, .dark)
}
private func deleteRow(at indexSet: IndexSet){
self.taskLabels.remove(atOffsets: indexSet)
}
}
//struct TasksView_Previews: PreviewProvider {
// static var previews: some View {
// TasksView()
// }
//}
TimerView Code ->
//
// TimerView.swift
// ProDActivity
//
// Created by Vivek Pattanaik on 5/27/21.
//
import SwiftUI
struct TimerView: View {
let lineWidth : CGFloat = 11
let radius : CGFloat = 150
// to pass into the struct
// #State var taskTime = 300
#State var defaultTimeRemaining : Float
#State var timeRemaining : Float
#State private var isActive = false
#State private var showButtons = false
#State private var stopAlert = false
#State private var pausePressed = false
#State private var stopPressed = false
// #State private var timeRemainingSeconds : CGFloat = 25
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
// self.defaultTimeRemaining = timerInfo.timerMinutes
VStack(spacing : 60) {
ZStack{
RoundedRectangle(cornerRadius: 7)
.frame(width: 300, height: 70)
.foregroundColor(Color("TabBar "))
}
ZStack(alignment: Alignment(horizontal: .center, vertical: .center)) {
Circle()
.stroke(Color.gray, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round))
.opacity(0.2)
Circle()
.trim(from: 1 - CGFloat(((defaultTimeRemaining-timeRemaining)/defaultTimeRemaining)), to: 1 )
.stroke(Color.accentColor, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round))
.rotationEffect( .degrees(-90))
.animation(.easeInOut)
// VStack for the timer and seesions
VStack {
// Text("\(Int(timeRemaining)):\(Int(timeRemainingSeconds))")
Text("\(timeString(time: Int(timeRemaining)))")
.font(.system(size: 50)).fontWeight(.medium)
Text("0 of 5 Sessions")
.font(.system(size: 20)).fontWeight(.medium)
}
}.frame(width: radius*2, height: radius*2)
// BEGIN, STOP, PAUSE BUTTONS
HStack(spacing: 25){
if showButtons == false {
Button(action: {
}, label: {
ZStack {
Rectangle()
.frame(width: 176, height: 55, alignment: .center)
.foregroundColor(Color.accentColor)
.cornerRadius(5)
Button(action: {
self.showButtons.toggle()
isActive.toggle()
}, label: {
Text("BEGIN")
.foregroundColor(Color.white)
.font(.system(size: 23).weight(.medium))
.frame(width: 176, height: 55, alignment: .center)
})
}
})
} else if showButtons == true {
HStack {
ZStack {
Rectangle()
.frame(width: 152, height: 55, alignment: .center)
.foregroundColor(Color("LightDark"))
.cornerRadius(5)
.border(Color.accentColor, width: 2)
Button(action: {
self.stopPressed.toggle()
self.pausePressed = true
if isActive == true {
isActive.toggle()
self.stopAlert = true
} else {
self.stopAlert = true
}
}, label: {
Text("STOP")
.foregroundColor(Color.accentColor)
.font(.system(size: 23).weight(.medium))
.frame(width: 152, height: 55, alignment: .center)
})
.alert(isPresented: $stopAlert) {
Alert(title: Text("Are you sure you want to stop?"),
message: Text("This will stop the timer and task associated with it."),
primaryButton: .destructive(Text("Yes"), action: {
self.showButtons = false
timeRemaining = defaultTimeRemaining
}),
secondaryButton: .cancel({
isActive = false
pausePressed = true
})
)
}
}
ZStack {
Rectangle()
.frame(width: 152, height: 55, alignment: .center)
.foregroundColor(pausePressed ? Color.accentColor : Color("LightDark"))
.cornerRadius(5)
.border(pausePressed ? Color.accentColor : Color.accentColor, width: 2)
Button(action: {
pausePressed.toggle()
if pausePressed == true {
isActive = false
} else {
isActive = true
}
}, label: {
Text("\(pausePressed ? "RESUME" : "PAUSE")")
.foregroundColor(pausePressed ? Color("TabBar ") : Color.accentColor)
.font(.system(size: 23).weight(.medium))
.frame(width: 152, height: 55, alignment: .center)
})
}
}
}
}
}.onReceive(timer, perform: { _ in
guard isActive else {return}
if timeRemaining > 0 {
timeRemaining -= 1
} else {
isActive = false
showButtons = false
self.timer.upstream.connect().cancel()
}
})
}
func timeString(time: Int) -> String {
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i:%02i", minutes, seconds)
}
}
//struct TimerView_Previews: PreviewProvider {
// static var previews: some View {
// TimerView()
// }
//}
//func buttonChange(){
//
//}

SwiftUI Segmented Picker does not switch when click on it

I'm trying to implement Segmented Control with SwiftUI. For some reason Segmented Picker does not switch between values when click on it. I went through many tutorials but cannot find any difference from my code:
struct MeetingLogin: View {
#State private var selectorIndex: Int = 0
init() {
UISegmentedControl.appearance().backgroundColor = UIColor(named: "JobsLightGreen")
UISegmentedControl.appearance().selectedSegmentTintColor = UIColor(named: "AlmostBlack")
UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white,
.font: UIFont(name: "OpenSans-Bold", size: 13)!],
for: .selected)
UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white,
.font: UIFont(name: "OpenSans-Regular", size: 13)!],
for: .normal)
}
var body: some View {
VStack {
...
Group {
Spacer().frame(minHeight: 8, maxHeight: 30)
Picker("video", selection: $selectorIndex) {
Text("Video On").tag(0)
Text("Video Off").tag(1)
}
.pickerStyle(SegmentedPickerStyle())
.padding([.leading, .trailing], 16)
Spacer().frame(minHeight: 8, maxHeight: 50)
Button(action: { self.sendPressed() }) {
ZStack {
RoundedRectangle(cornerRadius: 100)
Text("go")
.font(.custom("Roboto-Bold", size: 36))
.foregroundColor(Color("MeetingGreen"))
}
}
.foregroundColor(Color("MeetingLightGreen").opacity(0.45))
.frame(width: 137, height: 73)
}
Spacer()
}
}
}
Would appreciate any suggestions!
Update: The issue seem to have occured due to overlapping of the View's because the cornerRadius value of RoundedRectangle was set to 100. Bringing the value of cornerRadius to 55 would restore the Picker's functionality.
The issue seems to be caused because of the RoundedRectangle(cornerRadius: 100) within the ZStack. I don't have and explanation as to why this is happening. I'll add the reason if I ever find out. Could be a SwiftUI bug. I can't tell untill I find any related evidence. So here is the code that could make the SegmentedControl work without any issue.
struct MeetingLogin: View {
//...
#State private var selectorIndex: Int = 0
var body: some View {
VStack {
//...
Group {
Spacer().frame(minHeight: 8, maxHeight: 30)
Picker("video", selection: $selectorIndex) {
Text("Video On").tag(0)
Text("Video Off").tag(1)
}
.pickerStyle(SegmentedPickerStyle())
.padding([.leading, .trailing], 16)
Spacer().frame(minHeight: 8, maxHeight: 50)
Button(action: { self.sendPressed() }) {
ZStack {
RoundedRectangle(cornerRadius: 55)
Text("go")
.font(.custom("Roboto-Bold", size: 36))
.foregroundColor(Color("MeetingGreen"))
}
}
.foregroundColor(Color("MeetingLightGreen").opacity(0.45))
.frame(width: 137, height: 73)
}
Spacer()
}
}
}
Xcode 12 iOS 14
you can get it by adding a if-else condition on the tapGesture of your Segment Control(Picker)
#State private var profileSegmentIndex = 0
Picker(selection: self.$profileSegmentIndex, label: Text("Jamaica")) {
Text("My Posts").tag(0)
Text("Favorites").tag(1)
}
.onTapGesture {
if self.profileSegmentIndex == 0 {
self.profileSegmentIndex = 1
} else {
self.profileSegmentIndex = 0
}
}
.pickerStyle(SegmentedPickerStyle())
.padding()
If you need to use it with more than 2 segments, you can try with an Enum :)
Your code/View is missing the if-condition to know what shall happen when the selectorIndex is 0 or 1.
It has to look like this:
var body: some View {
VStack {
if selectorIndex == 0 {
//....Your VideoOn-View
} else {
//Your VideoOff-View
}
}

SwiftUI list animations

I am following Apple's Swift UI Animating Views And Transitions and I noticed a bug in the Hike Graph View. When I click on the graph it does not allow me to switch from Elevation to Heart Rate or Pace. It does not let me and just exits the view. I think this has something to do with the List here:
VStack(alignment: .leading) {
Text("Recent Hikes")
.font(.headline)
HikeView(hike: hikeData[0])
}
Hike View Contains:
import SwiftUI
struct HikeView: View {
var hike: Hike
#State private var showDetail = false
var transition: AnyTransition {
let insertion = AnyTransition.move(edge: .trailing)
.combined(with: .opacity)
let removal = AnyTransition.scale
.combined(with: .opacity)
return .asymmetric(insertion: insertion, removal: removal)
}
var body: some View {
VStack {
HStack {
HikeGraph(hike: hike, path: \.elevation)
.frame(width: 50, height: 30)
.animation(nil)
VStack(alignment: .leading) {
Text(hike.name)
.font(.headline)
Text(hike.distanceText)
}
Spacer()
Button(action: {
withAnimation {
self.showDetail.toggle()
}
}) {
Image(systemName: "chevron.right.circle")
.imageScale(.large)
.rotationEffect(.degrees(showDetail ? 90 : 0))
.scaleEffect(showDetail ? 1.5 : 1)
.padding()
}
}
if showDetail {
HikeDetail(hike: hike)
.transition(transition)
}
}
}
}
Hike Detail Contains:
struct HikeDetail: View {
let hike: Hike
#State var dataToShow = \Hike.Observation.elevation
var buttons = [
("Elevation", \Hike.Observation.elevation),
("Heart Rate", \Hike.Observation.heartRate),
("Pace", \Hike.Observation.pace),
]
var body: some View {
return VStack {
HikeGraph(hike: hike, path: dataToShow)
.frame(height: 200)
HStack(spacing: 25) {
ForEach(buttons, id: \.0) { value in
Button(action: {
self.dataToShow = value.1
}) {
Text(value.0)
.font(.system(size: 15))
.foregroundColor(value.1 == self.dataToShow
? Color.gray
: Color.accentColor)
.animation(nil)
}
}
}
}
}
}
Hike Graoh Contains:
import SwiftUI
func rangeOfRanges<C: Collection>(_ ranges: C) -> Range<Double>
where C.Element == Range<Double> {
guard !ranges.isEmpty else { return 0..<0 }
let low = ranges.lazy.map { $0.lowerBound }.min()!
let high = ranges.lazy.map { $0.upperBound }.max()!
return low..<high
}
func magnitude(of range: Range<Double>) -> Double {
return range.upperBound - range.lowerBound
}
extension Animation {
static func ripple(index: Int) -> Animation {
Animation.spring(dampingFraction: 0.5)
.speed(2)
.delay(0.03 * Double(index))
}
}
struct HikeGraph: View {
var hike: Hike
var path: KeyPath<Hike.Observation, Range<Double>>
var color: Color {
switch path {
case \.elevation:
return .gray
case \.heartRate:
return Color(hue: 0, saturation: 0.5, brightness: 0.7)
case \.pace:
return Color(hue: 0.7, saturation: 0.4, brightness: 0.7)
default:
return .black
}
}
var body: some View {
let data = hike.observations
let overallRange = rangeOfRanges(data.lazy.map { $0[keyPath: self.path] })
let maxMagnitude = data.map { magnitude(of: $0[keyPath: path]) }.max()!
let heightRatio = (1 - CGFloat(maxMagnitude / magnitude(of: overallRange))) / 2
return GeometryReader { proxy in
HStack(alignment: .bottom, spacing: proxy.size.width / 120) {
ForEach(data.indices) { index in
GraphCapsule(
index: index,
height: proxy.size.height,
range: data[index][keyPath: self.path],
overallRange: overallRange)
.colorMultiply(self.color)
.transition(.slide)
.animation(.ripple(index: index))
}
.offset(x: 0, y: proxy.size.height * heightRatio)
}
}
}
}
Graph Capsule Contains:
import SwiftUI
struct GraphCapsule: View {
var index: Int
var height: CGFloat
var range: Range<Double>
var overallRange: Range<Double>
var heightRatio: CGFloat {
max(CGFloat(magnitude(of: range) / magnitude(of: overallRange)), 0.15)
}
var offsetRatio: CGFloat {
CGFloat((range.lowerBound - overallRange.lowerBound) / magnitude(of: overallRange))
}
var body: some View {
Capsule()
.fill(Color.white)
.frame(height: height * heightRatio)
.offset(x: 0, y: height * -offsetRatio)
}
}
Is there any way to fix this? Thanks
The problem might be deeper in SwiftUI - if you comment out transition(.slide) in HikeGraph (and restart the XCODE), it will start working

SwiftUI Button: Preserve highlighted state without ugly animation

I have a quiz view with buttons per answer. After the user chooses an answer, the respective button should remain highlighted. The problem is that I get an unwanted transition animation, it seems that the following happens
User holds button: isPressed = true
User taps button: isPressed = false
Button action is triggered: answerState == .highlighted
This results in an animation where the button is unhighlighted in step 2 and highlighted again in step 3, which is quite ugly. Do you have any idea how to solve that issue?
import Foundation
import SwiftUI
struct QuizView: View {
#State var quizQuestion = QuizManager.shared.generateQuestion()
#State var selectedAnswer: Insignia? = nil
#State var isSolutionPresented = false
#Environment(\.verticalSizeClass) var verticalSizeClass: UserInterfaceSizeClass?
#Environment(\.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?
var body: some View {
QuizGrid(self.quizQuestion.elements) { quizElement in
if quizElement.type == .question {
VStack {
Text("Group name")
.font(.subheadline)
.fontWeight(.light)
.padding(.horizontal)
Text(quizElement.insignia.wrappedName)
.font(.title)
// .font(.system(size: 30.0, weight: .heavy, design: .default))
//.fontWeight(.heavy)
//.lineLimit(2)
.multilineTextAlignment(.center)
.fixedSize(horizontal: false, vertical: true)
.padding(.horizontal)
.padding(.top, 5)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
Button(action: {
self.selectedAnswer = quizElement.insignia
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.presentSolution()
}
}) {
Image("Image")
.renderingMode(.original)
}
.buttonStyle(
QuizAnswerButtonStyle(answerState: self.answerState(answer: quizElement.insignia))
)
.disabled(self.selectedAnswer != nil)
}
}
.gridStyle(
(horizontalSizeClass == .compact && verticalSizeClass == .regular) ? QuizGridStyle(columns: 2, rows: 2, questionPosition: .top, relativeQuestionSize: CGSize(width:1, height: 0.3)) : QuizGridStyle(columns: 4, rows: 1, questionPosition: .top, relativeQuestionSize: CGSize(width:1, height: 0.3))
)
}
struct QuizAnswerButtonStyle: ButtonStyle {
var answerState: QuizAnswerState
func makeBody(configuration: Self.Configuration) -> some View {
ZStack(alignment: .init(horizontal: .center, vertical: .center)) {
Rectangle()
.foregroundColor(.white)
.colorMultiply(self.fillColor(answerState: (configuration.isPressed || self.answerState == .highlighted) ? .highlighted : self.answerState))
configuration.label
}
.overlay(
RoundedRectangle(cornerRadius: 10)
.strokeBorder(Color("quizItemBorderColor").opacity(0.2), lineWidth: 1)
)
.cornerRadius(10)
}
func fillColor(answerState: QuizAnswerState) -> Color {
switch(answerState) {
case .neutral:
return Color("quizItemNeutralColor")
case .highlighted:
return Color("quizItemHighlightedColor")
case .correct:
return Color("quizItemCorrectColor")
case .incorrect:
return Color("quizItemIncorrectColor")
}
}
}
func answerState(answer: Insignia) -> QuizAnswerState {
if self.isSolutionPresented {
if (self.selectedAnswer?.objectID == answer.objectID && answer.objectID == self.quizQuestion.question.objectID) || (self.selectedAnswer?.objectID != answer.objectID && answer.objectID == self.quizQuestion.question.objectID) {
return .correct
} else if self.selectedAnswer?.objectID == answer.objectID && answer.objectID != self.quizQuestion.question.objectID {
return .incorrect
}else {
return .neutral
}
} else {
return self.selectedAnswer?.objectID == answer.objectID ? .highlighted : .neutral
}
}
func presentSolution() {
withAnimation(.easeInOut(duration: 0.15)) {
self.isSolutionPresented = true
}
let delay = self.selectedAnswer?.objectID == self.quizQuestion.question.objectID ? UserDefaults.standard.double(forKey: "QuizDelayAfterCorrectAnswer") : UserDefaults.standard.double(forKey: "QuizDelayAfterIncorrectAnswer")
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
self.loadQuestion()
}
}
func loadQuestion() {
self.isSolutionPresented = false
self.selectedAnswer = nil
self.quizQuestion = QuizManager.shared.generateQuestion()
}
}
public enum QuizAnswerState {
case neutral
case highlighted
case correct
case incorrect
}
For the following demo, I added a scale animation for better visibility of the issue. The first interactions are just pressing the button without actually selecting it. The animation looks good. The last interaction is selecting the button, and there is this strange animation.