在SwiftUI中收藏夹后,如何保持按钮颜色



我希望我的收藏夹按钮根据用户喜欢还是不喜欢一个角色来切换颜色。我能够将文本从";收藏夹"至";有利的";并且最初改变颜色。如果我退出应用程序,按钮颜色将恢复到原始颜色。我的计算属性中有更改颜色的逻辑,但不知道当用户打开和关闭应用程序时如何保持它。

这是我的密码。

import SwiftUI
struct CharacterDetailsView: View {


var character: Character

@EnvironmentObject var favorites: Favorites


@State private var isFavorited = false



var favoriteText: String {
if isFavorited  {
return "Favorited"
} else {
return "Favorite"
}
}

var favoriteButton: some View {
Button {
isFavorited.toggle()


if favorites.contains(character) {
//If favorites contains a character, we are trying to un-favorite and remove it
favorites.remove(character)
} else {
favorites.add(character)
}

} label: {
ZStack {
if isFavorited == false {
Capsule()
.strokeBorder(Color.green, lineWidth: 4)
.frame(width: 250, height: 50)
.background(
Capsule()
.fill(.green)
.cornerRadius(20)
)

} else {
Capsule()
.strokeBorder(Color.blue, lineWidth: 4)
.frame(width: 250, height: 50)
.background(
Capsule()
.fill(.blue)
.cornerRadius(20)
)

}

HStack {
Text(favoriteText)
.foregroundColor(.white)
Image(systemName: favorites.contains(character) ? "heart.fill" : "heart")
.foregroundColor(favorites.contains(character) ? .white : .white)

}
}
}
.padding(.vertical)
}


var body: some View {
ScrollView {
VStack {
//MARK: - Image
AsyncImage(url: URL(string: character.image)) {
phase in
if let image = phase.image {
image
.resizable()
.scaledToFit()
} else if phase.error != nil {
Text("Couldn't upload photo")
} else {
ProgressView()
}
}

VStack(alignment: .leading) {
Text(character.name)
.font(.largeTitle)
.bold()
.padding(.leading)


favoriteButton

}
}

}



}

您需要从存储先前状态的环境对象(如(中恢复状态

favoriteButton
.onAppear {
isFavorite = favorites.contains(character)    // << here !!
}

最新更新