2

I am trying to create a Widget with SwiftUI, and I want to use the ".timer" style from Text but the result of the Text(entry.date, style: .timer) is something like 15:34:23

But I want the hour and minute part separately.

How can I achieve this?

I tried to get the string value of the text and format it in a method but It seems that there is no way to get Text String like we could do in Swift like someLabel.text

I also have found this question that is similar to mine but I couldn't find any answer there

And I don't want to use this solution either, because it takes a lot longer to load the widgets.

Thanks in advance.

pawello2222
  • 46,897
  • 22
  • 145
  • 209
Sasan Soroush
  • 857
  • 8
  • 16
  • Does this answer your question? [Updating time text label each minute in WidgetKit](https://stackoverflow.com/questions/64053733/updating-time-text-label-each-minute-in-widgetkit) – pawello2222 Oct 29 '20 at 20:50
  • Actually, I don't wanna use that solution because it takes a lot longer for the widget to be loaded this way. it works for simple widgets but my widget is a little bit complicated, with this solution it can take more than a few minutes to load but with the .timer method, it is instant because there is no need to add 60 * 24 entires in advance – Sasan Soroush Oct 29 '20 at 21:26
  • You can't change the `.timer` format, so you may need to create entries in advance. – pawello2222 Oct 29 '20 at 21:29
  • Is there any way to get the Text string as we could do in Swift like someLabel.text? – Sasan Soroush Oct 29 '20 at 21:31
  • No. And the problem here is that Widget views are *static*. You can't refresh them from inside the view itself. You need to reload the timeline. If you don't want to create entries for the whole day (as you say it's slow), you can create them for an hour only and reload after. – pawello2222 Oct 29 '20 at 21:37
  • I tried that solution but after an hour, when it tries to get new timeline entries it doesn't do it right away and has some delays, do you happen to experience this too? – Sasan Soroush Oct 29 '20 at 22:35
  • This answer might help you: https://stackoverflow.com/a/64014799/8697793 – pawello2222 Oct 29 '20 at 22:40

1 Answers1

0
Text(Calendar.current.startOfDay(for: Date()), style: .timer)

But the hour is not displayed at 0 o'clock, and only one-digit hour is displayed before 10 o'clock.

Jason Zhao
  • 11
  • 3
  • But I just want to grab the minute part of it – Sasan Soroush Nov 18 '20 at 14:50
  • My question was how to change the format but it is still showing the original format of hh:mm:ss – Sasan Soroush Nov 18 '20 at 14:51
  • My code is to display the hour:minute:second between the current time and 0 points. For example, if the current time is 10:20 in the morning, then the distance from 0 is 10 hours and 20 minutes. The format is the default HH:mm:ss and cannot be modified. – Jason Zhao Nov 19 '20 at 15:13