简体   繁体   中英

Published computed property in SwiftUI is not updating

I have a class:

    class ItemController: ObservableObject {
    init() {
        self.current = 0 // The first object of the array by default
        self.itemPrices = [1000, 1200, 1320, 1000, 1200, 1320, 2000, 2300] // The array itself
        thePrice = {
            return self.itemPrices[self.current % 8] // Here's the computed property I want to work and by updated by a function
        }
    }
   
    var current: Int // Simply the current object of the array
    let itemPrices: [Int] // The array I initialised higher
    @Published public var thePrice: () -> Int = {return 0} // The computed property 

    func moveItem() { // this function should change the "current" while other @Published stuff changes automatically 
        self.current += 1
        print(self.itemPrices[current])
    }
}

Also there is a view like:

struct ContentView: View {
    var item = ItemController()
    var body: some View {
        Text(String(self.item.thePrice()))
        Button("next") { item.moveItem() } // this button starts the function
    }
}

When I press the button the Text should change but it doesn't, though basically it looks correct.

What you have published is not a computed property but a function so to get an update published you would need to assign a new function to the property and that is not what you want.

Make your published property hold the price directly instead and modify it in the moveItem method.

 @Published var price: Int

Change your init to

init() {
    self.current = 0
    self.itemPrices = [1000, 1200, 1320, 1000, 1200, 1320, 2000, 2300]
    price = itemPrices[current]
}

and then update moveItem . Note that you need to check for index out of bounds error so I added a simple suggestion

func moveItem() {
    self.current += 1
    if current >= itemPrices.count { current == 0 }
    price = itemPrices[current]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM