无法快速更改 @State 变量的值?

发布于 2025-01-09 10:43:32 字数 961 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小耗子 2025-01-16 10:43:32

如果您密切注意错误消息,编译器不会抱怨 rexShape 不可变,而是抱怨 CGRect.height 不可变。

要更改 CGRect 的唯一 heightweight,您需要通过其 size 属性来完成。

rexShape.size.height -= 10

If you pay close attention to the error message, the compiler isn't complaining about rexShape not being mutable, but about CGRect.height not being mutable.

To change the only height or weight of a CGRect, you need to do it via its size property.

rexShape.size.height -= 10
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文