Reputation: 636
I'm building a clock app.
I'm trying to separate my views and I'm partially successful.
I can pass my clock item to ClockView
.
However, I cannot pass the currentTime
to ClockView.
//ContentView.swift
import SwiftUI
import SDWebImageSwiftUI
struct ContentView: View {
@State var clocks: [Clock] = []
var width = UIScreen.main.bounds.width
//@State var currentTime = Time(min: 0, sec: 0, hour: 0)
@State var receiver = Timer.publish(every: 1, on: .current, in: .default).autoconnect()
var body: some View {
NavigationView{
ScrollView {
LazyVGrid{
ForEach(clocks, id: \.id) { clock in
Button(action: {
print("login tapped")
}) {
ClockView(clock: clock)
//ClockView(clock: clock, time:Time(min: 0, sec: 0, hour: 0)) this does not work
}
}
NavigationLink(destination: SubscriptionView(),
isActive: $subscriptionScreenIsActivated){
}
.frame(width: width / 2, height: width / 2)
}.padding(15)
}.navigationTitle("Analog Clocks")
}.onAppear {
apiCall().getClocks { (clocks) in
self.clocks = clocks
}
}
.onReceive(receiver) { (_) in
let calender = Calendar.current
let min = calender.component(.minute, from : Date())
let sec = calender.component(.second, from : Date())
let hour = calender.component(.hour, from : Date())
withAnimation(Animation.linear(duration: 0.01)) {
self.currentTime = Time(min: min, sec: sec, hour: hour)
}
}
}
}
func getTime()->String{
let format = DateFormatter()
format.dateFormat = "hh:mm a"
return format.string(from: Date())
}
struct Time {
var min : Int
var sec : Int
var hour : Int
}
I want to use currentTime
in following view.
//ClockView.swift
import SwiftUI
import SDWebImageSwiftUI
struct ClockView: View {
var width = UIScreen.main.bounds.width
var clock: Clock
// var currentTime = Time
var body: some View {
ZStack{
WebImage(url: URL(string: clock.sec_hand.img))
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 32.0, height:width - 370.0)
.offset(y: (width - 500) / 4)
// .rotationEffect(.init(degrees: Double(currentTime.sec) * 6)) //Cannot use currentTime
}
}
}
I also tried environmentObject
but it did not work either.
//ContentView.swift
ClockView(clock: clock)
.environmentObject(time: Time(min: 0, sec: 0, hour: 0))
//ClockView.swift
@EnvironmentObject var currentTime: Time
How can I pass the currentTime
from ContentView
to ClockView
correctly?
Upvotes: 0
Views: 48
Reputation: 36274
it really depends what you want to achieve, but to pass the currentTime to ClockView, you can do this:
in "ClockView" setup "@Binding var currentTime: Time",
In "ContentView" have "@State var currentTime = Time(min: 0, sec: 0, hour: 0)"
and use "ClockView(clock: clock, currentTime: $currentTime)"
Upvotes: 2