わからないこと
ViewModelにあるDrink
のdrink.cups
とStepper
の値をバインディングしたいです。
SwiftUIを用いて、Stepperを使おうとしたのですが
61行目のようにStepperを使おうとすると
Cannot convert value of type 'Published<UInt>.Publisher' to expected argument type 'Binding<_>'
とエラーが出てしまいます。
環境
- Xcode 11.3
- Swift 5.13
ソースコード
import SwiftUI
import Foundation
import Combine
class Drink: ObservableObject, Identifiable {
@ObservedObject var viewModel: ContentViewModel
let id: String = UUID().uuidString
let name: String //名前
let one_of_caffein_amount: float_t //一杯あたりのカフェインの量[mg]
@Published var cups: UInt //個数
init(name: String, cups: UInt, one_of_caffein_amount: float_t) {
self.name = name
self.one_of_caffein_amount = one_of_caffein_amount
self.cups = 0
}
}
final class ContentViewModel: ObservableObject{
@Published var caffein_amuont_sum: float_t = 0
@Published var drinks: [Drink] = [
.init(name: "インスタントコーヒー", cups: 0, one_of_caffein_amount: 108.0),
.init(name: "缶コーヒー", cups: 0, one_of_caffein_amount: 40.0),
.init(name: "紅茶", cups: 0, one_of_caffein_amount: 45.0),
]
func Addcaffein(drink: Drink) {
caffein_amuont_sum += drink.one_of_caffein_amount
}
func Removecaffein(drink: Drink) {
caffein_amuont_sum -= drink.one_of_caffein_amount
}
}
//セル
struct DrinkItem: View {
@ObservedObject var viewModel: ContentViewModel
var drink: Drink
var body: some View {
HStack {
Text(drink.name)
Spacer()
//ERROR!!
Stepper(value: drink.$cups, in: 0 ... 99, label: {Text(" \(drink.$cups) 個")})
}
.padding(EdgeInsets(top: 3.0, leading: 20.0, bottom: 3.0, trailing: 20.0))
}
}
//全体
struct ContentView: View {
@ObservedObject var viewModel: ContentViewModel
var body: some View {
VStack {
Spacer()
Text("計 0g")
Spacer()
List(viewModel.drinks) { drink in
DrinkItem(viewModel: self.viewModel, drink: drink)
}
}
.navigationBarTitle("Caffein Checker", displayMode: .inline)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(viewModel: ContentViewModel())
}
}