我有一个名为Players的Coredata实体,它具有以下属性:
- name(类型String)
- scorelvel1 (of type Integer16)
- scorelvel2 (of type Integer16)
- scorelvel3 (of type Integer16)
- scoretotal (of type of Integer16)
我希望scoretotal等于scorelvel1 + scorelvel2 + scorelvel3
这样做可能吗?
My Model是这样的:
extension Players {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Players> {
return NSFetchRequest<Players>(entityName: "Players")
}
@NSManaged public var name: String?
@NSManaged public var scorelevel1: Int16
@NSManaged public var scorelevel2: Int16
@NSManaged public var scorelevel3: Int16
@NSManaged public var scoretotal: Int16
public var wrappedName: String {
name ?? "player unknown"
}
}
extension Players : Identifiable {
}
然后我有一个MainUIView调用PlayerView(见下文),我希望能够在每个关卡输入每个玩家的分数,我想自动求和每个关卡的分数,并将总分存储在我的coredata属性"scoretotal";
MainUIView是这样的
struct MainUIView: View {
@Environment(.managedObjectContext) var moc
@FetchRequest(entity: Players.entity(), sortDescriptors: [
NSSortDescriptor(keyPath: Players.name, ascending: false)
]) var players: FetchedResults<Players>
var body: some View {
HStack{
ForEach(players, id: .wrappedName) { player in
PlayerView(player: player)
}
}
}
和PlayerView是这样的:
struct PlayerView: View {
@ObservedObject var player:Players
@Environment(.managedObjectContext) var moc
var body: some View {
VStack {
Text(player.wrappedName)
TextField("Score", value: $player.scorelevel1, formatter:NumberFormatter())
TextField("Score", value: $player.scorelevel2, formatter:NumberFormatter())
TextField("Score", value: $player.scorelevel3, formatter:NumberFormatter())
}
}
}
**我想添加的是一个"文本",在VStack的最后一行,这将是总和美元的球员。Scorelevel1 + $player。Scorelevel2 + $player.scorelevel3
并将其存储在$player.scoretotal** 中我是SwiftUI的新手,我不知道该怎么做。我试图在PlayerView中声明一个像这样的变量:
var total: Int16 {
$player.scorelevel1 + $player.scorelevel2 + $player.scorelevel3
}
但是我有一个错误消息说:二元运算符"+"不能应用于两个"绑定"操作数"和没有"+"候选者产生预期的上下文结果类型"Int16">
无论如何,这看起来不像是正确的方法,即使它工作,我也不知道如何分配变量"total"player.scoretotal"美元;…
我还试图在我的模型中声明一个计算属性,通过这样做:
@NSManaged public var scoretotal: Int16 {
scorelevel1 + scorelevel2 + scorelevel3
}
但是我有错误消息说&;@NSManaged不允许在computed properties&;
如果有人能帮我做那件事,我将非常感激。谢谢和问候。JB删除
@NSManaged
使一个常规计算机变量。这个变量不需要我管理/存储