Changing color of UI with onTapGesture - ios

I've been trying to find a way to change the color of every flashcard in my app. I am struggling with understanding how to use #Binding, which I believe is the best solution. I ended up creating static variables in my Card struct, which allows me to change the card colors via onTapGesture actions. It seems very slow and I know there has to be a better way to accomplish this. Below is my code. The action for changing the color is inside the Circle() in ContentView. Thank you in advance. Also could someone please tell me how to resize screenshots to post in here? The solutions online make my screenshots super blurry so I hate uploading them
CardView
import SwiftUI
struct CardView: View {
let card: Card
var removal: (() -> Void)? = nil
#State private var isShowingAnswer = false
#State private var changeColors = false
#State private var offset = CGSize.zero
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 25, style: .continuous)
.fill(LinearGradient(colors: [Card.gradCs[Card.selec][0].opacity(1 - Double(abs(offset.width / 50))), Card.gradCs[Card.selec][1].opacity(1 - Double(abs(offset.width / 50)))], startPoint: .topLeading, endPoint: .bottomTrailing))
.background(RoundedRectangle(cornerRadius: 25, style: .continuous).fill(offset.width > 0 ? .green : .red))
.shadow(color: Color(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.25)), radius:6, x:1, y:8)
VStack(spacing: 20){
Text(card.prompt)
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(.white.opacity(0.8))
if isShowingAnswer {
Text(card.answer)
.font(.title)
.fontWeight(.semibold)
.foregroundColor(Color(#colorLiteral(red: 0.8947916626930237, green: 0.8666666746139526, blue: 1, alpha: 1)))
}
}
.padding()
.multilineTextAlignment(.center)
}
.frame(width: 450, height: 250)
.rotationEffect(.degrees(Double(offset.width / 5)))
.offset(x: offset.width * 5, y: 0)
.opacity(2 - Double(abs(offset.width / 50)))
.gesture(
DragGesture()
.onChanged { gesture in
offset = gesture.translation
}
.onEnded { _ in
if abs(offset.width) > 100 {
removal?()
} else {
offset = .zero
}
}
)
.onTapGesture {
isShowingAnswer.toggle()
}
}
}
struct CardView_Previews: PreviewProvider {
static var previews: some View {
CardView(card: Card.example)
.previewInterfaceOrientation(.portraitUpsideDown)
}
}
ContentView
import SwiftUI
extension View {
func stacked(at position: Int, in total: Int) -> some View {
let offset = Double(total - position)
return self.offset(x: 0, y: offset * 10)
}
}
struct ContentView: View {
#Environment(\.accessibilityDifferentiateWithoutColor) var differentiateWithoutColor
#State private var cards = Array(repeating: Card.example, count: 10)
#State private var timeRemaining = 100
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
#Environment(\.scenePhase) var scenePhase
#State private var isActive = true
var body: some View {
ZStack {
VStack {
HStack {
Text("\(timeRemaining / 60):\(timeRemaining % 60, specifier: "%02d")")
.font(.title)
.fontWeight(.semibold)
.foregroundColor(.white)
.padding(.horizontal, 20)
.padding(.vertical, 5)
.background(.black.opacity(0.75))
.clipShape(Capsule())
Circle()
.fill(LinearGradient(colors: Card.gradCs[Card.selec], startPoint: .topLeading, endPoint: .bottomTrailing))
.onTapGesture {
withAnimation {
if Card.selec == 0 {
Card.selec = 1
} else {
Card.selec = 0
}
}
}
.frame(width: 40, height: 40)
}
ZStack {
ForEach(0 ..< cards.count, id: \.self) { index in
CardView(card: cards[index]) {
withAnimation {
removeCard(at: index)
print(self.offset())
}
}
.stacked(at: index, in: cards.count)
}
}
.allowsHitTesting(timeRemaining > 0)
if cards.isEmpty {
Button("Start Again", action: resetCards)
.padding()
.background(.white)
.foregroundColor(.black)
.clipShape(Capsule())
}
}
if differentiateWithoutColor {
VStack {
Spacer()
HStack {
Image(systemName: "xmark.circle")
.padding()
.background(.black.opacity(0.7))
.clipShape(Circle())
Spacer()
Image(systemName: "checkmark.circle")
.padding()
.background(.black.opacity(0.7))
.clipShape(Circle())
}
.foregroundColor(.white)
.font(.largeTitle)
.padding()
}
}
}
.onReceive(timer) { time in
guard isActive else { return }
// Use if let when the non-nil case is valid. Use guard when the nil case represents some sort of error.
// use guard when there should only be one result.. use if when you need ELSE to do something
if timeRemaining > 0 {
timeRemaining -= 1
}
}
.onChange(of: scenePhase) { newPhase in
if newPhase == .active {
if cards.isEmpty == false {
isActive = true
}
} else {
isActive = false
}
}
}
func removeCard(at index: Int) {
cards.remove(at: index)
if cards.isEmpty {
isActive = false
}
}
func resetCards() {
cards = Array(repeating: Card.example, count: 10)
timeRemaining = 100
isActive = true
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Card
import Foundation
import SwiftUI
struct Card {
let prompt: String
let answer: String
static var example = Card(prompt: "What is the name of Chicago's NFL Team?", answer: "Da Bears")
static var gradCs = [[Color(#colorLiteral(red: 0.6039215922355652, green: 0.49803921580314636, blue: 1, alpha: 1)), Color(#colorLiteral(red: 1, green: 0.49803924560546875, blue: 1, alpha: 1))], [Color(#colorLiteral(red: 0.6039215922355652, green: 1, blue: 1, alpha: 1)), Color(#colorLiteral(red: 0.6039215922355652, green: 0.49803921580314636, blue: 1, alpha: 1))]]
static var selec = 0
}

binding is a possible way to change colors, but I prefer the use of ObservableObject
to manage the set of Cards and their color selection.
The code in my answer shows how to use a ObservableObject CardManager to change all cards color
resulting from your selection in Circle.
// manages the cards and all cards color selection
class CardManager: ObservableObject {
let gradCs = [[Color(#colorLiteral(red: 0.6039215922355652, green: 0.49803921580314636, blue: 1, alpha: 1)), Color(#colorLiteral(red: 1, green: 0.49803924560546875, blue: 1, alpha: 1))], [Color(#colorLiteral(red: 0.6039215922355652, green: 1, blue: 1, alpha: 1)), Color(#colorLiteral(red: 0.6039215922355652, green: 0.49803921580314636, blue: 1, alpha: 1))]]
#Published var cards = [Card]()
#Published var selec = 0
func getColorSet() -> [Color] {
return gradCs[selec]
}
}
struct Card {
let prompt: String
let answer: String
static var example = Card(prompt: "What is the name of Chicago's NFL Team?", answer: "Da Bears")
}
extension View {
func stacked(at position: Int, in total: Int) -> some View {
let offset = Double(total - position)
return self.offset(x: 0, y: offset * 10)
}
}
struct ContentView: View {
#Environment(\.accessibilityDifferentiateWithoutColor) var differentiateWithoutColor
#StateObject var manager = CardManager() // <--- here
#State private var timeRemaining = 100
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
#Environment(\.scenePhase) var scenePhase
#State private var isActive = true
var body: some View {
ZStack {
VStack {
HStack {
Text("\(timeRemaining / 60):\(timeRemaining % 60, specifier: "%02d")")
.font(.title)
.fontWeight(.semibold)
.foregroundColor(.white)
.padding(.horizontal, 20)
.padding(.vertical, 5)
.background(.black.opacity(0.75))
.clipShape(Capsule())
Circle()
.fill(LinearGradient(colors: manager.getColorSet(), startPoint: .topLeading, endPoint: .bottomTrailing))
.onTapGesture {
withAnimation {
if manager.selec == 0 {
manager.selec = 1
} else {
manager.selec = 0
}
}
}
.frame(width: 40, height: 40)
}
ZStack {
ForEach(0 ..< manager.cards.count, id: \.self) { index in
CardView(card: manager.cards[index]) {
withAnimation {
removeCard(at: index)
print(self.offset())
}
}
.stacked(at: index, in: manager.cards.count)
}
}
.allowsHitTesting(timeRemaining > 0)
if manager.cards.isEmpty {
Button("Start Again", action: resetCards)
.padding()
.background(.white)
.foregroundColor(.black)
.clipShape(Capsule())
}
}
if differentiateWithoutColor {
VStack {
Spacer()
HStack {
Image(systemName: "xmark.circle")
.padding()
.background(.black.opacity(0.7))
.clipShape(Circle())
Spacer()
Image(systemName: "checkmark.circle")
.padding()
.background(.black.opacity(0.7))
.clipShape(Circle())
}
.foregroundColor(.white)
.font(.largeTitle)
.padding()
}
}
}
.onReceive(timer) { time in
guard isActive else { return }
// Use if let when the non-nil case is valid. Use guard when the nil case represents some sort of error.
// use guard when there should only be one result.. use if when you need ELSE to do something
if timeRemaining > 0 {
timeRemaining -= 1
}
}
.onChange(of: scenePhase) { newPhase in
if newPhase == .active {
if manager.cards.isEmpty == false {
isActive = true
}
} else {
isActive = false
}
}
.onAppear {
manager.cards = Array(repeating: Card.example, count: 10) // <--- here
}
.environmentObject(manager) // <--- here
}
func removeCard(at index: Int) {
manager.cards.remove(at: index)
if manager.cards.isEmpty {
isActive = false
}
}
func resetCards() {
manager.cards = Array(repeating: Card.example, count: 10)
timeRemaining = 100
isActive = true
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct CardView: View {
#EnvironmentObject var manager: CardManager // <--- here
let card: Card
var removal: (() -> Void)? = nil
#State private var isShowingAnswer = false
#State private var changeColors = false
#State private var offset = CGSize.zero
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 25, style: .continuous)
.fill(LinearGradient(colors: [manager.getColorSet()[0].opacity(1 - Double(abs(offset.width / 50))), manager.getColorSet()[1].opacity(1 - Double(abs(offset.width / 50)))], startPoint: .topLeading, endPoint: .bottomTrailing))
.background(RoundedRectangle(cornerRadius: 25, style: .continuous).fill(offset.width > 0 ? .green : .red))
.background(RoundedRectangle(cornerRadius: 25, style: .continuous).fill(offset.width > 0 ? .green : .red))
.shadow(color: Color(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.25)), radius:6, x:1, y:8)
VStack(spacing: 20){
Text(card.prompt)
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(.white.opacity(0.8))
if isShowingAnswer {
Text(card.answer)
.font(.title)
.fontWeight(.semibold)
.foregroundColor(Color(#colorLiteral(red: 0.8947916626930237, green: 0.8666666746139526, blue: 1, alpha: 1)))
}
}
.padding()
.multilineTextAlignment(.center)
}
.frame(width: 450, height: 250)
.rotationEffect(.degrees(Double(offset.width / 5)))
.offset(x: offset.width * 5, y: 0)
.opacity(2 - Double(abs(offset.width / 50)))
.gesture(
DragGesture()
.onChanged { gesture in
offset = gesture.translation
}
.onEnded { _ in
if abs(offset.width) > 100 {
removal?()
} else {
offset = .zero
}
}
)
.onTapGesture {
isShowingAnswer.toggle()
}
}
}

Related

SwiftUI: Reset "Slide to Unlock" button after drag gesture

I want to make my slider go back to its original position after I have unlocked it once by dragging to the end.
The animation goes till the end and stays there.
I want it to go back to its initial position once the unlock swipe is complete, meaning once the unlock lock image is shown, it should reset to again being locked.
How can I achieve this?
I am attaching complete code. It has three components, Dragging component and background component that are being called in main Unlock button view.
//
// DraggingComponent.swift
// VirtualDoorman
//
// Created by Engr. Bushra on 11/9/22.
//
import SwiftUI
struct DraggingComponent: View {
#Binding var isLocked: Bool
let isLoading: Bool
let maxWidth: CGFloat
private let minWidth = CGFloat(50)
#State private var width = CGFloat(50)
var duration: Double = 0.3
var body: some View {
RoundedRectangle(cornerRadius: 16)
.fill(Color.red)
.opacity(width / maxWidth)
.frame(width: width)
.overlay(
Button(action: { }) {
ZStack {
image(name: "lock", isShown: isLocked)
progressView(isShown: isLoading)
image(name: "lock.open", isShown: !isLocked && !isLoading)
}
.animation(.easeIn(duration: 0.35).delay(0.55), value: !isLocked && !isLoading)
}
.buttonStyle(BaseButtonStyle())
.disabled(!isLocked || isLoading),
alignment: .trailing
)
.simultaneousGesture (
DragGesture()
.onChanged { value in
guard isLocked else { return }
if value.translation.width > 0 {
width = min(max(value.translation.width + minWidth, minWidth), maxWidth)
}
}
.onEnded { value in
guard isLocked else { return }
if width < maxWidth {
width = minWidth
UINotificationFeedbackGenerator().notificationOccurred(.warning)
} else {
UINotificationFeedbackGenerator().notificationOccurred(.success)
withAnimation(.spring().delay(0.5)) {
isLocked = false
// DispatchQueue.main.asyncAfter(deadline: .now() + duration + 0.2) {
// withAnimation(.easeOut(duration: duration)) {
// width = min(max(value.translation.width + minWidth, minWidth), maxWidth)
//
// }
// }
// isLocked = true
}
}
}
)
.animation(.spring(response: 0.5, dampingFraction: 1, blendDuration: 0), value: width)
}
private func image(name: String, isShown: Bool) -> some View {
Image(systemName: name)
.font(.system(size: 20, weight: .regular, design: .rounded))
.foregroundColor(Color("BlueAccent"))
.frame(width: 42, height: 42)
.background(RoundedRectangle(cornerRadius: 14).fill(.white))
.padding(4)
.opacity(isShown ? 1 : 0)
.scaleEffect(isShown ? 1 : 0.01)
}
private func progressView(isShown: Bool) -> some View {
ProgressView()
.progressViewStyle(.circular)
.tint(.white)
.opacity(isShown ? 1 : 0)
.scaleEffect(isShown ? 1 : 0.01)
}
}//struct
//struct DraggingComponent_Previews: PreviewProvider {
// static var previews: some View {
// DraggingComponent(maxWidth: 10)
// }
//}
struct BaseButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.scaleEffect(configuration.isPressed ? 0.95 : 1)
.opacity(configuration.isPressed ? 0.9 : 1)
.animation(.default, value: configuration.isPressed)
}
}
//
// BackgroundComponent.swift
// VirtualDoorman
//
// Created by Engr. Bushra on 11/9/22.
//
import SwiftUI
struct BackgroundComponent: View {
#State private var hueRotation = false
var body: some View {
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: 16)
.fill(LinearGradient(
colors: [Color("BlueAccent").opacity(0.8), Color("BlueAccent").opacity(0.8)],
startPoint: .leading,
endPoint: .trailing
)
)
.hueRotation(.degrees(hueRotation ? 20 : -20))
Text("Slide to unlock")
.font(.footnote)
.bold()
.foregroundColor(.white)
.frame(maxWidth: .infinity)
}
.onAppear {
withAnimation(.linear(duration: 3).repeatForever(autoreverses: true)) {
hueRotation.toggle()
}
}
}
}
struct BackgroundComponent_Previews: PreviewProvider {
static var previews: some View {
BackgroundComponent()
}
}
extension Color {
static let pinkBright = Color(red: 247/255, green: 37/255, blue: 133/255)
static let blueBright = Color(red: 67/255, green: 97/255, blue: 238/255)
static let blueDark = Color(red: 58/255, green: 12/255, blue: 163/255)
}
//
// Unlock_Button.swift
// VirtualDoorman
//
// Created by Engr. Bushra on 11/9/22.
//
import SwiftUI
struct Unlock_Button: View {
#State private var isLocked = true
#State private var isLoading = false
var completion: (() -> Void)?
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .leading) {
BackgroundComponent()
DraggingComponent(isLocked: $isLocked, isLoading: isLoading, maxWidth: geometry.size.width)
}
}
.frame(height: 50)
.padding()
.onChange(of: isLocked) { isLocked in
guard !isLocked else { return }
simulateRequest()
}
}
private func simulateRequest() {
isLoading = true
// completion?()
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
isLoading = false
}
}
}
struct Unlock_Button_Previews: PreviewProvider {
static var previews: some View {
Unlock_Button()
}
}

Pause the timer with a button

I am making a timer but am unsure of how to pause it when the button is triggered.
I have attempted to make a boolean #State but I am yet unsure how to pause the timer when the button is triggered. Please review my code below...
struct TestView: View {
#State var isTimeStarted = false
#State var to: CGFloat = 0
#State var timeDuration = 60
#State var time = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
#State var isPaused = false
#State private var count = 0
var body: some View {
ZStack {
VStack {
ZStack {
Circle()
.trim(from: 0, to: self.to)
.stroke(LinearGradient(gradient: Gradient(colors: [Color.white, Color.white.opacity(0.2)]), startPoint: .topLeading, endPoint: .bottomTrailing), style: StrokeStyle(lineWidth: 15.6, lineCap: .round))
.shadow(radius: 8)
.rotationEffect(.degrees(90))
.rotation3DEffect(Angle(degrees: 180), axis: (x: 1, y: 0, z: 110))
.frame(width: 70, height: 70)
.animation(.easeOut)
.padding()
.padding(.leading, 10)
Text("\(self.timeDuration, specifier: formatTime())")
.font(.system(size: 17.5, design: .rounded))
.fontWeight(.semibold)
.foregroundColor(.white)
.padding(.leading, 10)
}
Button {
isPaused = true
} label: {
ZStack {
BlurView2(style: .systemThinMaterialDark)
.frame(width: 145, height: 45)
.background(Color.yellow)
.cornerRadius(30)
.padding(.horizontal)
Image(systemName: "pause")
.font(.title2)
.shadow(radius: 10)
.foregroundColor(.yellow)
}
}
}
}
.preferredColorScheme(.dark)
.onAppear {
self.timeDuration = 60
withAnimation(.default) {
self.to = 60
}
self.isTimeStarted = true
}
.onReceive(self.time, perform: { _ in
if self.timeDuration != 0 {
self.timeDuration -= 1
withAnimation(.default) {
self.to = CGFloat(self.timeDuration)/60
}
} else {
self.timeDuration = 60
self.to = 60
}
})
}
func formatTime() -> String {
let minutes = Int(timeDuration) / 60 % 60
let seconds = Int(timeDuration) % 60
return String(format: "%02i:%02i", minutes,seconds)
}
}
struct BlurView2: UIViewRepresentable {
var style: UIBlurEffect.Style
func makeUIView(context: Context) -> UIVisualEffectView {
let view = UIVisualEffectView(effect: UIBlurEffect(style: style))
return view
}
func updateUIView(_ uiView: UIVisualEffectView, context: Context) {
}
}
Thi should be pretty simple. Keep your timer firing but return in your function if it should pause.
Add this to the start of your .onReceive function:
if isPaused{
return
}
and change your Button to:
isPaused.toggle()

I can't modify circular progress bar trim in SwiftUI

I'm making a math game and I'm trying to implement a circular progress bar, where I get errors. I'm not sure if I'm doing anything wrong, but I can't adapt it to the progress of the game, and that's what I want to do. Please look over my code down below...
struct QuestionView: View {
#State var show = false
#State var showSheet: Bool = false
#State var showSheetA: Bool = false
#State var showSheet2: Bool = false
#State private var correctAnswer = 0
#State private var choiceArray: [Int] = [0, 1, 2, 3]
#State private var firstNumber = 0
#State private var secondNumber = 0
#State private var difficulty = 100
#State private var score = 0
#State private var Background1 = "Background 1"
#State private var Background2 = "Background 2"
#State private var Background3 = "Background 3"
#State private var Background4 = "Background 4"
#State private var Background5 = "Background 5"
#State private var Background6 = "Background 6"
#State private var Background7 = "Background 7"
#State private var Background8 = "Background 8"
#State private var Background9 = "Background 9"
#State private var Background10 = "Background 10"
#State private var Background11 = "Background 11"
#State private var Background12 = "Background 12"
#State private var background = [
"Background 1",
"Background 2",
"Background 3",
"Background 4",
"Background 5",
"Background 6",
"Background 7",
"Background 8",
"Background 9",
"Background 10",
"Background 11",
"Background 12",
]
#State var value = "0"
let buttons: [[CalcButton]] = [
[.clear, .negative, .percent, .divide],
[.seven, .eight, .nine, .multiply],
[.four, .five, .six, .subtract],
[.one, .two, .three, .add],
[.zero, .decimal, .equal]
]
#State var currentOperation: Operation = .none
#State var runningNumber = 0
var body: some View {
ZStack {
Image("\(Background1)")
.resizable()
.aspectRatio(contentMode: .fill)
.edgesIgnoringSafeArea(.all)
.blur(radius: 20)
.onAppear {
shuffle()
}
VStack {
VStack(alignment: .leading) {
HStack {
HStack {
Circle()
//Where the problem is happening at the trim
.trim(from: CGFloat(show ? Int(0.99) : answerIsCorrect(answer: correctAnswer)), to: 0.01)
.stroke(LinearGradient(gradient: Gradient(colors: [Color.white, Color.white.opacity(0.2)]), startPoint: .topLeading, endPoint: .bottomTrailing), style: StrokeStyle(lineWidth: 17.5, lineCap: .round))
.shadow(radius: 8)
.rotationEffect(.degrees(90))
.rotation3DEffect(Angle(degrees: 180), axis: (x: 1, y: 0, z: 0))
.frame(width: 60, height: 60)
.animation(.easeOut)
.padding()
.padding([.top, .leading])
Spacer()
}
Button {
showSheet.toggle()
} label: {
VStack {
ZStack {
Rectangle()
.fill(.thinMaterial)
.frame(width: 80, height: 40)
.cornerRadius(30)
.padding(.top, 13)
.padding(.trailing, 0)
HStack {
Image(systemName: "circle.grid.3x3.fill")
.foregroundColor(.white)
.font(.title3)
.padding(.top, 13)
.padding(.trailing, 0)
}
}
Text("CALCULATOR")
.font(.system(size: 11))
.padding(.trailing, 0)
}
}
.halfSheet(showSheet: $showSheet) {
ZStack {
Color.black.opacity(0.925).ignoresSafeArea()
VStack {
Spacer()
// Text display
HStack {
Spacer()
Text(value)
.bold()
.font(.system(size: 70))
.foregroundColor(.white)
.minimumScaleFactor(0.5)
}
.padding(.leading)
.padding([.top, .trailing], 23)
.padding(.bottom, 2)
// Our Buttons
ForEach(buttons, id: \.self) { row in
HStack(spacing: 12) {
ForEach(row, id: \.self) { item in
Button {
self.didTap(button: item)
} label: {
Text(item.rawValue)
.font(.system(size: 36))
.frame(width: self.buttonWidth(item: item), height: 55)
.scaledToFit()
.background(item.buttonColor)
.foregroundColor(.white)
.cornerRadius(95)
}
}
}
.padding(.bottom, 0.55)
.padding([.leading, .trailing], 20)
}
}
}
}
Button {
showSheet2.toggle()
} label: {
VStack {
ZStack {
Rectangle()
.fill(.thinMaterial)
.frame(width: 80, height: 40)
.cornerRadius(30)
.padding(.top, 13)
.padding(.trailing, 28.5)
HStack {
Image(systemName: "book")
.foregroundColor(.white)
.font(.title3)
.padding(.top, 13)
.padding(.trailing, 28.5)
}
}
Text("DICTIONARY")
.font(.system(size: 11))
.padding(.trailing, 25.5)
}
}
.halfSheet(showSheet: $showSheet2) {
ZStack {
Home()
}
}
}
.padding(.top, 50)
}
VStack {
Text("Solve the following:")
.foregroundColor(.white)
.font(.title2)
.fontWeight(.medium)
.padding(.bottom, 24)
Text("\(firstNumber) + \(secondNumber)")
.foregroundColor(.white)
.font(.system(size: 60, design: .rounded))
.fontWeight(.medium)
.padding(.bottom, 28)
.onAppear {
generateAnswers()
}
VStack(alignment: .center, spacing: 0.01) {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 2.5)]) {
ForEach(0..<4, id: \.self) { index in
Button {
answerIsCorrect(answer: choiceArray[index])
generateAnswers()
} label: {
AnswerButton(number: choiceArray[index])
}
}
}
Spacer()
}
HStack {
Button {
} label: {
ZStack {
Rectangle()
.fill(Color.white.opacity(0.5))
.frame(maxWidth: 150, maxHeight: 50)
.cornerRadius(15)
.padding([.leading, .trailing])
Image(systemName: "chevron.left")
.font(.title)
}
}
Button {
showSheetA.toggle()
} label: {
VStack {
ZStack {
Rectangle()
.fill(Color.white.opacity(0.5))
.frame(maxWidth: 150, maxHeight: 50)
.cornerRadius(15)
.padding([.leading, .trailing])
Image(systemName: "xmark")
.font(.title)
.foregroundColor(.red)
}
}
}
ZStack {
Rectangle()
.fill(Color.white.opacity(0.5))
.frame(maxWidth: 150, maxHeight: 50)
.cornerRadius(15)
.padding([.leading, .trailing])
Image(systemName: "chevron.right")
.font(.title)
}
}
.padding(.trailing, 6)
.padding(.bottom)
Spacer(minLength: 65)
}
}
}
}
func shuffle() {
Background1 = background[Int.random(in: background.indices)]
Background2 = background[Int.random(in: background.indices)]
Background3 = background[Int.random(in: background.indices)]
Background4 = background[Int.random(in: background.indices)]
Background5 = background[Int.random(in: background.indices)]
Background6 = background[Int.random(in: background.indices)]
Background7 = background[Int.random(in: background.indices)]
Background8 = background[Int.random(in: background.indices)]
Background9 = background[Int.random(in: background.indices)]
Background10 = background[Int.random(in: background.indices)]
Background11 = background[Int.random(in: background.indices)]
Background12 = background[Int.random(in: background.indices)]
}
func answerIsCorrect(answer: Int) {
let isCorrect = answer == correctAnswer ? true : false
if isCorrect {
self.score += 1
} else {
self.score -= 1
}
}
func generateAnswers() {
firstNumber = Int.random(in: 0...(difficulty/2))
secondNumber = Int.random(in: 0...(difficulty/2))
var answerList = [Int]()
correctAnswer = firstNumber + secondNumber
for i in 0...2 {
answerList.append(Int.random(in: 0...difficulty))
}
answerList.append(correctAnswer)
choiceArray = answerList.shuffled()
}
func didTap(button: CalcButton) {
switch button {
case .add, .subtract, .multiply, .divide, .equal:
if button == .add {
self.currentOperation = .add
self.runningNumber = Int(self.value) ?? 0
} else if button == .subtract {
self.currentOperation = .subtract
self.runningNumber = Int(self.value) ?? 0
} else if button == .multiply {
self.currentOperation = .multiply
self.runningNumber = Int(self.value) ?? 0
} else if button == .divide {
self.currentOperation = .divide
self.runningNumber = Int(self.value) ?? 0
} else if button == .equal {
let runningValue = self.runningNumber
let currentValue = Int(self.value) ?? 0
switch self.currentOperation {
case .add:
self.value = "\(runningValue + currentValue)"
case .subtract:
self.value = "\(runningValue - currentValue)"
case .multiply:
self.value = "\(runningValue * currentValue)"
case .divide:
self.value = "\(runningValue / currentValue)"
case .none:
break
}
}
if button != .equal {
self.value = "0"
}
case .clear:
self.value = "0"
case .decimal, .percent, .negative:
break
default:
let number = button.rawValue
if self.value == "0" {
value = number
} else {
self.value = "\(self.value)\(number)"
}
}
}
func buttonWidth(item: CalcButton) -> CGFloat {
if item == .zero {
return ((UIScreen.main.bounds.width - (4*12)) / 4) * 2
}
return (UIScreen.main.bounds.width - (5*12)) / 4
}
func buttonHeight() -> CGFloat {
return (UIScreen.main.bounds.height - (5*12)) / 4
}
}
struct AnswerButton: View {
var number: Int
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill(Color.white.opacity(0.6))
.frame(maxWidth: .infinity, minHeight: 110)
.cornerRadius(15)
.padding([.leading, .trailing], 10)
.padding(.top)
.padding(.trailing, 6)
Text("\(number)")
.font(.largeTitle)
.fontWeight(.medium)
.foregroundColor(.primary)
.padding([.leading, .trailing], 10)
.padding(.top)
.padding(.trailing, 6)
}
}
}
enum CalcButton: String {
case one = "1"
case two = "2"
case three = "3"
case four = "4"
case five = "5"
case six = "6"
case seven = "7"
case eight = "8"
case nine = "9"
case zero = "0"
case add = "+"
case subtract = "-"
case divide = "÷"
case multiply = "×"
case equal = "="
case clear = "AC"
case decimal = "."
case percent = "%"
case negative = "+/-"
var buttonColor: Color {
switch self {
case .add, .subtract, .multiply, .divide, .equal:
return .orange
case .clear, .negative, .percent:
return .gray
default:
return Color(UIColor(red: 55/255.0, green: 55/255.0, blue: 55/255.0, alpha: 1))
}
}
}
enum Operation {
case add, subtract, multiply, divide, none
}
extension View {
func halfSheet<SheetView: View>(showSheet: Binding<Bool>, #ViewBuilder sheetView: #escaping () -> SheetView) -> some View {
return self
.background(
HalfSheetHelper(sheetView: sheetView(), showSheet: showSheet)
)
}
}
struct HalfSheetHelper<SheetView: View>: UIViewControllerRepresentable {
var sheetView: SheetView
#Binding var showSheet: Bool
class Coordinator {
let dummyController = UIViewController()
let sheetController: CustomHostingController<SheetView>
init(sheetView: SheetView, showSheet: Binding<Bool>) {
sheetController = CustomHostingController(rootView: sheetView, onDismiss: { showSheet.wrappedValue = false })
dummyController.view.backgroundColor = .clear
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(sheetView: sheetView, showSheet: $showSheet)
}
func makeUIViewController(context: Context) -> UIViewController {
return context.coordinator.dummyController
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
context.coordinator.sheetController.rootView = sheetView
if showSheet && uiViewController.presentedViewController == nil {
uiViewController.present(context.coordinator.sheetController, animated: true)
}
}
}
class CustomHostingController<Content: View>: UIHostingController<Content> {
var onDismiss: (() -> Void)?
convenience init(rootView: Content, onDismiss: #escaping () -> Void) {
self.init(rootView: rootView)
self.onDismiss = onDismiss
}
override func viewDidLoad() {
if let presentationController = presentationController as? UISheetPresentationController {
presentationController.detents = [
.large(),
.medium()
]
presentationController.prefersGrabberVisible = true
}
}
override func viewDidDisappear(_ animated: Bool) {
onDismiss?()
}
}
struct QuestionView_Previews: PreviewProvider {
static var previews: some View {
QuestionView()
}
}
Thank you for looking at my code. I look forward to your answer!
struct ContentView: View {
#State private var progress: Double = 0.1
var body: some View {
VStack {
Circle()
.trim(from: 0, to: progress)
.stroke(lineWidth: 20)
.rotationEffect(Angle(degrees: 180))
.shadow(radius: 8)
.rotationEffect(.degrees(90))
.frame(width: 60, height: 60)
.padding()
Slider(value: $progress, in: 0...1)
.padding()
}
}
}

Print the selected value in the TextField

I created an ActionSheet, but was unable to print the value I selected on the TextField.
I do not know how to do it. I will be glad if you can help.
struct illedetayyip: View {
#State private var iliskiDurumlari: [String] = ["Evli", "Bekar", "Ayrı", "anan"]
#State private var iliskiArray = NSMutableArray()
#State private var iliskiVisible = false
#State private var iliski = ""
func iliskiFunc() {
for i in 0 ..< self.iliskiDurumlari.count {
let button: ActionSheet.Button = .default(Text(self.iliskiDurumlari[i]), action: {
print(self.iliskiDurumlari[i])
})
self.iliskiArray[i] = button
}
}
init() {
iliskiFunc()
}
var body: some View {
VStack {
TextField("İlişki Durumu Seçiniz..", text: $iliski)
.frame(width: 300, height: 50, alignment: .center)
.padding(5)
.font(Font.system(size: 15, weight: .medium, design: .serif))
.overlay(RoundedRectangle(cornerRadius: 30).stroke(Color(red: 45 / 255,
green: 0 / 255, blue: 112 / 255), lineWidth: 1))
.actionSheet(isPresented: $iliskiVisible) {
ActionSheet(title: Text("Bir İlişki Durumu Seçiniz"), message:
Text("Aşagıda"), buttons: self.iliskiArray as! [ActionSheet.Button])
}
.onTapGesture {
self.iliskiVisible.toggle()
}
}
}
}
You don't need to create a NSMutableArray and then cast it back to [ActionSheet.Button].
Try this instead:
struct illedetayyip: View {
#State private var iliskiDurumlari: [String] = ["Evli", "Bekar", "Ayrı", "anan"]
#State private var iliskiVisible = false
#State private var iliski = ""
var body: some View {
VStack {
TextField("İlişki Durumu Seçiniz..", text: $iliski)
.frame(width: 300, height: 50, alignment: .center)
.padding(5)
.font(Font.system(size: 15, weight: .medium, design: .serif))
.overlay(
RoundedRectangle(cornerRadius: 30)
.stroke(Color(red: 45 / 255, green: 0 / 255, blue: 112 / 255), lineWidth: 1)
)
.actionSheet(isPresented: $iliskiVisible, content: actionSheet)
.onTapGesture {
self.iliskiVisible.toggle()
}
}
}
func actionSheet() -> ActionSheet {
ActionSheet(
title: Text("Bir İlişki Durumu Seçiniz"),
message: Text("Aşagıda"),
buttons: iliskiDurumlari.map { value in
ActionSheet.Button.default(Text(value), action: {
self.iliski = value
})
}
)
}
}

How to customize row internal content with List in SwiftUI combining collapsable rows?

This is a follow-up question to the following topic.
How can I fix the "Hello World" card inside the row to the top of its cell? It shouldn't move when the second card is coming out by tapping.
Current State:
But inside the row cell it should be alignment to it's top like sketched in this image:
struct ContentView: View {
var body: some View {
VStack {
Text("Hello!")
List {
Detail(isExpanded: false)
Detail(isExpanded: false)
Detail(isExpanded: false)
}
}
}
}
struct Detail: View {
#State var isExpanded :Bool = false
var body: some View {
VStack {
ZStack (alignment: .bottom){
ZStack (alignment: .center) {
RoundedRectangle(cornerRadius: 8)
.fill(Color(red: 0.0, green: 1.0, blue: 1.0, opacity: 0.5)).frame(height: 115)
Text("Helloo!")
}.zIndex(3).frame(height: 115).contentShape(Rectangle()).onTapGesture {
withAnimation (.linear(duration: 0.1)){
self.isExpanded.toggle()
}
}
Button(action: {
}) {
ZStack {
RoundedRectangle(cornerRadius: 50)
.fill(Color(red: 1.0, green: 0.0, blue: 1.0, opacity: 0.5)).frame(height: 70)
.cornerRadius(8)
.shadow(radius: 3)
Text("Test")
}
}.padding([.leading, .trailing], 12)
//.padding(.top, 6)
.frame(height: 70)
.buttonStyle(BorderlessButtonStyle())
.offset(y: self.isExpanded ? 80 : 0)
.disabled(!self.isExpanded)
}
if(self.isExpanded) {
Spacer()
}
}.modifier(AnimatingCellHeight(height: self.isExpanded ? 210 : 115)).background(Color(red: 1.0, green: 0.5, blue: 1, opacity: 0.5))
}
}
struct AnimatingCellHeight: AnimatableModifier {
var height: CGFloat = 0
var animatableData: CGFloat {
get { height }
set { height = newValue }
}
func body(content: Content) -> some View {
content.frame(height: height)
}
}
EDIT
The end result should look like this. The inverted isExpanded Bool is my fault...should be the other way around.
EDIT 2 Code above is updated to the newest try. which you will see in the gif below.
Almost got there....The blue card which I am pressing to expand is moving a little bit up and down (you can clearly see when increasing the click frequency) in the following gif. Otherwise the behaviour is perfect, just the card should do this little wiggle up and down...
do you mean this way? (added VStack + Spacer)
struct Detail: View {
#State var isExpanded :Bool = false
var body: some View {
VStack {
ZStack {
ZStack {
RoundedRectangle(cornerRadius: 8)
.fill(Color(red: 0.0, green: 1.0, blue: 1.0, opacity: 1.0)).frame(height: 115)
Text("Hello!")
}.zIndex(3).frame(height: 115).contentShape(Rectangle()).onTapGesture {
withAnimation {
self.isExpanded.toggle()
}
}
Button(action: {
}) {
ZStack {
RoundedRectangle(cornerRadius: 50)
.fill(Color(red: 1.0, green: 0.0, blue: 1.0, opacity: 1.0)).frame(height: 70)
.cornerRadius(8)
.shadow(radius: 3)
Text("Test")
}
}.padding([.leading, .trailing], 12)
.padding(.top, 6)
.frame(height: 70)
.buttonStyle(BorderlessButtonStyle())
.offset(y: self.isExpanded ? 0 : 40)
.disabled(!self.isExpanded)
}
Spacer()
}.modifier(AnimatingCellHeight(height: self.isExpanded ? 120 : 200))
}
}

Resources