【问题标题】:Fill entire screen with a color using Timer - SwiftUI使用 Timer 用颜色填充整个屏幕 - SwiftUI
【发布时间】:2021-08-07 08:50:30
【问题描述】:

我正在尝试使用计时器并用颜色填充屏幕。简单地说:我用\(UIScreen.main.bounds.height)获取屏幕高度,然后用selectedTime除以\(120)秒。问题出现在这里:屏幕填满了 232,而不是 844.0 屏幕尺寸,它在 32 秒而不是 120 秒内填满。我可能错过了一些东西。相关代码部分:

.onChange(of: secondsToMinutesAndSeconds(seconds: timerManager.secondsLeft), perform: { waveTime in
            
            let selectedCircularValue = availableMinutes[self.selectedCircularIndex] * 60
            let heightProgress = CGFloat(UIScreen.main.bounds.height / CGFloat(selectedCircularValue))
            if timerManager.screenHeightChanged < UIScreen.main.bounds.height {
                
                timerManager.screenHeightChanged += CGFloat(heightProgress)
                withAnimation(.linear) {
                    
                    self.colorSize = CGFloat(Double(timerManager.screenHeightChanged))
                }
            } else {
                timerManager.screenHeightChanged = 0
            }
        })

进度输出

 { seconds 120
        screenHeight 844.0
        estimatedTime screen / seconds -> (7.033333333333333)
        ...
        progress 14.066666666666666
        ...
        progress 225.06666666666663
        ...
        progress 232.09999999999997
        
        }

最后,是否可以让动画变得流畅?

Mine

My expectation

【问题讨论】:

标签: swift swiftui timer countdowntimer swiftui-animation


【解决方案1】:

根据我的经验,UIScreen 可能会很烦人。尝试改用 GeometryReader,它在处理 SwiftUI 视图时效果更好。像这样包裹视图

GeometryReader { geo in
    SomeView()
}
.frame(width: .infinity, height: .infinity) //may not need this

然后,当您想要视图的大小时,只需使用 geo.size.widthgeo.size.height

对于动画,将withAnimation 函数与.animation(.linear) 等修饰符结合使用。

由于您没有分享最小的可重现示例,因此我无法分享完整的解决方案或针对您的案例测试我的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 2019-10-22
    • 2015-06-16
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多