SwiftUI - Dynamic Island - Why does the dynamic island takes the whole horizontal space in compact mode?
Asked Answered
V

1

6

I have a stopwatch running in a dynamic island compact mode, using the same font and color. The first screenshot is an idle stopwatch, and the second screenshot is a running stopwatch.

Idle state: enter image description here

Running state: enter image description here

I believe the correct state should be the first screenshot.

Code (inside compactTrailing block):

if stopwatch.isRunning {
  // Stopwatch running state
  Text(timerInterval: stopwatch.timeInterval, countsDown: false)
    .font(.system(size: 14, weight: .medium))
    .foregroundColor(iconTintDarkMode)
} else {
  // Stopwatch idle state
  Text(timerString(time: stopwatch.elapsedTime))
    .font(.system(size: 14, weight: .medium))
    .foregroundColor(iconTintDarkMode)
}

timerString method:

func timerString(time: Double) -> String {
  var result = ""
  let hours = Int(time) / 3600
  let minutes = Int(time) / 60 % 60
  let seconds = Int(time) % 60

  if hours > 0 {
    result.append(String(format: "%02d:", hours))
  }
  result.append(String(format: "%02d:%02d", minutes, seconds))
  return result
}

Does anyone know why the difference is?

Vauban answered 5/2, 2023 at 10:39 Comment(0)
V
4

That's a good question. Got the same issue. I tried some things and ended up with this:

Text(Date().addingTimeInterval(300), style: .timer)    
  .frame(maxWidth: .minimum(50, 50), alignment: .leading)
  .background(.red)

This works for me. But the minimum x / y value depends on how big the Text view will be. I set the background to red, so you have a better understanding how much space this solution takes. But for me it looks like a bug in the timer styled text.

Vertigo answered 28/2, 2023 at 22:20 Comment(3)
thank you for sharing! Let's hope for improvements in the upcoming OS updates.Vauban
For what it's worth, this seems to be a bug in SwiftUI developer.apple.com/forums/thread/713446Steffi
A more dynamic solution that resizes the Text view based on its current value https://mcmap.net/q/522664/-widgetkit-timer-text-style-expands-it-to-fill-the-width-instead-of-taking-space-to-fit-the-contained-stringWongawonga

© 2022 - 2024 — McMap. All rights reserved.