无法快速更改 @State 变量的值?
Swift 5.x iOS 15
只是尝试一个想法并遇到障碍?为什么我无法在此代码中更改此状态变量的值?
struct ContentView: View {
let timer = Timer.publish(every: 0.25, on: .main, in: .common).autoconnect()
@State var rexShape = CGRect(x: 0, y: 0, width: 128, height: 128)
var body: some View {
Arc(startAngle: .degrees(0), endAngle: .degrees(180), clockwise: true)
.stroke(Color.red, lineWidth: 2)
.frame(width: 128, height: 128, alignment: .center)
.onReceive(timer) { _ in
rexShape.height -= 10
}
}
}
struct Arc: Shape {
var startAngle: Angle
var endAngle: Angle
var clockwise: Bool
func path(in rect: CGRect) -> Path {
var path = Path()
path.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: rect.width / 2, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise)
return path
}
}
rexShape.height 行告诉我高度是仅获取属性?这对我来说毫无意义,因为 rexShape 应该是一个变量?难道我只是失去理智了吗……
Swift 5.x iOS 15
Just playing around with an idea and hit a roadblock? Why can I not change the value of this state variable in this code?
struct ContentView: View {
let timer = Timer.publish(every: 0.25, on: .main, in: .common).autoconnect()
@State var rexShape = CGRect(x: 0, y: 0, width: 128, height: 128)
var body: some View {
Arc(startAngle: .degrees(0), endAngle: .degrees(180), clockwise: true)
.stroke(Color.red, lineWidth: 2)
.frame(width: 128, height: 128, alignment: .center)
.onReceive(timer) { _ in
rexShape.height -= 10
}
}
}
struct Arc: Shape {
var startAngle: Angle
var endAngle: Angle
var clockwise: Bool
func path(in rect: CGRect) -> Path {
var path = Path()
path.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: rect.width / 2, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise)
return path
}
}
The line rexShape.height is telling me height is a get-only property? which makes no sense to me cause rexShape should be a variable? Am I simply losing my mind...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您密切注意错误消息,编译器不会抱怨
rexShape
不可变,而是抱怨CGRect.height
不可变。要更改
CGRect
的唯一height
或weight
,您需要通过其size
属性来完成。If you pay close attention to the error message, the compiler isn't complaining about
rexShape
not being mutable, but aboutCGRect.height
not being mutable.To change the only
height
orweight
of aCGRect
, you need to do it via itssize
property.