如何解决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 举报,一经查实,本站将立刻删除。