SwiftUI @State在教程中使用

问题描述

当我尝试教程的animating-views-and-transitions部分时,当我下载整个项目并单击“海拔”,“心率”和“步速”按钮时。它不会像教程中那样改变画布。相反,它保留了颜色,但“胶囊”的位置有所变化。

我猜@State可能不太正确,但是我不知道如何解决它。部分代码如下所示。整个项目为here

HikeDetail.swift此视图将@State传递给HikeGraph,HikeGraph将图片更改为该@State

struct HikeDetail: View {
    let hike: Hike
    @State var dataToShow = \Hike.Observation.elevation
    
    var buttons = [
        ("Elevation",\Hike.Observation.elevation),("Heart Rate",\Hike.Observation.heartRate),("Pace",\Hike.Observation.pace),]
    
    var body: some View {
        return VStack {
            HikeGraph(hike: hike,path: dataToShow)
                .frame(height: 200)
            
            HStack(spacing: 25) {
                ForEach(buttons,id: \.0) { value in
                    Button(action: {
                        self.dataToShow = value.1
                    }) {
                        Text(value.0)
                            .font(.system(size: 15))
                            .foregroundColor(value.1 == self.dataToShow
                                ? Color.gray
                                : Color.accentColor)
                            .animation(nil)
                    }
                }
            }
        }
    }
}

HikeGraph.swift。它应该随着HikeDetail传递的路径而改变颜色。但这不是

struct HikeGraph: View {
    var hike: Hike
    var path: KeyPath<Hike.Observation,Range<Double>>
    
    var color: Color {
        switch path {
        case \.elevation:
            return .gray
        case \.heartRate:
            return Color(hue: 0,saturation: 0.5,brightness: 0.7)
        case \.pace:
            return Color(hue: 0.7,saturation: 0.4,brightness: 0.7)
        default:
            return .black
        }
    }
    
    var body: some View {
        let data = hike.observations
        let overallRange = rangeOfRanges(data.lazy.map { $0[keyPath: self.path] })
        let maxMagnitude = data.map { magnitude(of: $0[keyPath: path]) }.max()!
        let heightRatio = (1 - CGFloat(maxMagnitude / magnitude(of: overallRange))) / 2

        return GeometryReader { proxy in
            HStack(alignment: .bottom,spacing: proxy.size.width / 120) {
                ForEach(data.indices) { index in
                    GraphCapsule(
                        index: index,height: proxy.size.height,range: data[index][keyPath: self.path],overallRange: overallRange)
                    .colorMultiply(self.color)
                    .transition(.slide)
                    .animation(.ripple(index: index))
                }
                .offset(x: 0,y: proxy.size.height * heightRatio)
            }
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...