![](/img/trans.png)
[英]Computed property from @Published array of objects not updating SwiftUI view
[英]SwiftUI: Computed Property from reusable View not working
使用 SwiftUI 框架,我创建了这个可重用的视图(减去了花里胡哨的样式):
struct RatingView: View {
let criteria: String
@State var rating: Int
var body: some View {
HStack {
Button {
if rating > 0 {
rating -= 1
}
} label: {
Image(systemName: "heart.slash.fill")
}
Spacer()
Text("\(criteria): \(rating)")
Spacer()
Button {
if rating < 1 {
rating += 1
}
} label: {
Image(systemName: "heart.fill")
}
}
}
}
并在这里实施(同样,没有花里胡哨的造型):
struct ScoringView: View {
let story = "Story"
let cheese = "Cheese"
let love = "Romance"
let actor = "In character"
var storyRating = 0
var cheesyRating = 0
var loveRating = 0
var actorRating = 0
var roundScore: Int {
storyRating + cheesyRating + loveRating + actorRating
}
var body: some View {
VStack {
RatingView(criteria: story, rating: storyRating)
RatingView(criteria: cheese, rating: cheesyRating)
RatingView(criteria: love, rating: loveRating)
RatingView(criteria: actor, rating: actorRating)
}
Spacer()
VStack {
Text("Score this round:")
Text("\(roundScore)")
}
}
}
无论我对评级按钮进行何种更改, roundScore
计算属性都不会更改并保持为零。
我在 Playground 中测试了计算属性,它可以工作,但是因为我无法在 SO 上找到任何关于计算属性和可重用视图组合的信息。 所以我想知道可重用视图是否让我感到困惑。
有什么想法吗?
你需要一些东西触发View
更新或 SwiftUI 不知道何时重绘。
添加@State
@State var storyRating = 0
@State var cheesyRating = 0
@State var loveRating = 0
@State var actorRating = 0
并将其从RatingView
中删除
@Binding var rating: Int
@State
是真实来源, @Binding
是双向连接。
您还必须在初始化视图时添加$
RatingView(criteria: story, rating: $storyRating)
RatingView(criteria: cheese, rating: $cheesyRating)
RatingView(criteria: love, rating: $loveRating)
RatingView(criteria: actor, rating: $actorRating)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.