【问题标题】:SwiftUI — How can I display a countdown in a ScrollView?SwiftUI — 如何在 ScrollView 中显示倒计时?
【发布时间】:2020-10-14 17:38:45
【问题描述】:

我正在尝试为 Apple Watch 制作一个 SwiftUI 应用程序,该应用程序需要在 ScrollView 中设置倒数计时器。但是,当我在 ScrollView 中放置日期格式化程序时,应用程序崩溃(至少在模拟器中 - 我无法在真实设备上进行测试,因为我的应用程序 ID 限制已经有几天了)。

代码如下:

struct ContentView: View {
    let date = Date()
    
    var body: some View {
        ScrollView {
            Text(date, style: .timer)
        }
    }
}

它给了我这个运行时错误:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

在一个名为SwiftUI.DisplayList.ViewUpdater.ViewCache.setNextUpdate(_:item:state:tag:)的函数中

【问题讨论】:

    标签: swift swiftui apple-watch watchos watchos-6


    【解决方案1】:

    这似乎是一个值得报告的错误。

    DateFormatter() 似乎是一个可行的解决方法。

    import SwiftUI
    
    struct TimerStyle: View {
        let date = Date()
        
        let timerFormat: DateFormatter
        
        init() {
            timerFormat = DateFormatter()
            timerFormat.dateFormat = "HH:mm:ss"
            
        }
        var body: some View {
            ScrollView {
                Text(date, formatter: timerFormat)
            }
        }
    }
    
    struct TimerStyle_Previews: PreviewProvider {
        static var previews: some View {
            TimerStyle()
        }
    }
    

    【讨论】:

      【解决方案2】:
      struct ContentView: View {
          var body: some View {
              ScrollView {
                  Text(Date(), style: .timer)
                      .clipped()
              }
          }
      }
      

      【讨论】:

        【解决方案3】:

        这就是答案!!!只需添加

        .clipped()

        struct ContentView: View {
            var body: some View {
                ScrollView {
                    Text(Date(), style: .timer)
                        .clipped()
                }
            }
        }
        

        【讨论】:

        • 请解释一下为什么会这样。
        • 这是一个神奇的错误,我不知道它是如何工作的
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多