You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中类属性变更后如何更新视图?

SwiftUI视图未随属性变更同步更新的解决方案

问题根源

  1. 未标记可发布属性:Produkt类的name和price属性没有添加@Published修饰符,属性变更时无法向SwiftUI发送更新通知。
  2. 错误的@StateObject位置:@StateObject被放在ContentView的body方法内,而body会被SwiftUI频繁调用,导致对象重复创建,无法正确维持状态。
  3. 视图结构缺失容器:create方法中的多个视图没有用布局容器(如HStack)包裹,不仅会编译报错,也无法正确渲染。

修改后的代码

修正后的Produkt类

class Produkt: ObservableObject {
    @Published var name: String
    @Published var price: Float
    
    init(name: String, price: Float) {
        self.name = name
        self.price = price
    }
    
    func increasePrice() {
        self.price = self.price * 1.5
    }
}

修正后的ContentView

struct ContentView: View {
    @StateObject private var kaffee = Produkt(name: "Kaffee", price: 1)
    
    var body: some View {
        HStack {
            Text("Preis: ")
            Text(String(kaffee.price))
            Spacer()
            Button("Upgrade") {
                kaffee.increasePrice()
                print(kaffee.price)
            }
        }
        .padding()
    }
}

关键说明

  • @Published修饰符会自动监听属性变化,当price被修改时,会通知SwiftUI刷新相关视图。
  • @StateObject放在ContentView的属性位置,确保对象在视图生命周期内只被创建一次,正确维护状态。
  • 用HStack包裹视图元素,符合SwiftUI的布局要求,确保视图正常渲染和更新。

内容的提问来源于stack exchange,提问作者Dadinana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 10:45:07