Добавление значений списка в SwiftUI для TotalValue - PullRequest
0 голосов
/ 31 января 2020

Вопрос здесь В процессе изучения SwiftUI, это приложение специально только для WatchOS. Итак, я создаю представление строки, которое затем использует представление карусели. У меня есть, поэтому, если вы нажмете на элемент списка, он попросит вас ввести ваш счет. Это, конечно, входит в строку (я мог бы sh, я мог бы получить его до go для int, но у меня не сработало бы.) Оценка кадров показывает себя хорошо. Тем не менее, я пытаюсь найти способ получить общий счет, чтобы добавить правильно.

Например,

Оценка 1 кадра 5 Общая оценка 5

Оценка 2 кадра 2 Общая оценка 7

Оценка 3 кадра 10 Общая оценка 17

...

Любая помощь будет высоко ценится благодаря

struct StartBowlingView: View {
    var body: some View {
        List{
            RowView(title: "1", framescore: "0", totalscore: "0")
            RowView(title: "2", framescore: "0", totalscore: "0")
            RowView(title: "3", framescore: "0", totalscore: "0")
            RowView(title: "4", framescore: "0", totalscore: "0")
            RowView(title: "5", framescore: "0", totalscore: "0")
            RowView(title: "6", framescore: "0", totalscore: "0")
            RowView(title: "7", framescore: "0", totalscore: "0")
            RowView(title: "8", framescore: "0", totalscore: "0")
            RowView(title: "9", framescore: "0", totalscore: "0")
            RowView(title: "10", framescore: "0", totalscore: "0")
        }
        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading)
        .navigationBarTitle("Frame")
        .listStyle(CarouselListStyle())
    }
}

struct RowView: View {
    @State var title: String
    @State var framescore:  String
    @State var totalscore: String

    var TotalScore: Int {
        let Totalframescore = Int(framescore) ?? 0
        return Totalframescore
    }

    var body: some View {
        NavigationLink(destination: TextField("Enter your Frame Score", text: $framescore) .border(Color.black))
        { //Start Frame List Design View
            VStack(alignment: .leading) {
                HStack(alignment: .center) {
                    Text(title)
                        .font(.system(.headline, design: .rounded))
                        .foregroundColor(Color.blue)
                        .multilineTextAlignment(.leading)
                    Divider()
                    Spacer()
                    Text("\(framescore)")
                        .font(.system(.body, design: .rounded))
                        .multilineTextAlignment(.leading)
                    Divider()
                    Spacer()
                    Text("\(TotalScore)")
                        .font(.system(.headline, design: .rounded))
                        .foregroundColor(Color.green)
                        .multilineTextAlignment(.trailing)
                }
            }
            .listRowBackground(Color.blue)
            .frame(height: 60, alignment: .topTrailing)
        }
    }
}

1 Ответ

0 голосов
/ 01 февраля 2020

Один подход может быть в каждой строке, чтобы уменьшить набор баллов до этой точки. Итерируя по множеству баллов, он может подсчитать номер кадра, балл кадра и сумму предыдущих баллов. Например, ваш основной вид может выглядеть следующим образом:

struct StartBowlingView: View {

    @State var frameScores = [5, 2, 10]

    var body: some View {
        List{
            ForEach(0..<self.frameScores.endIndex) { index in
                RowView(title: "\(index + 1)",
                    framescore: "\(self.frameScores[index])",
                    totalscore: "\(self.frameScores[0...index].reduce(0, { $0 + $1 }))")
            }
        }
    }
}

Я понимаю, что боулинг может быть более сложным, чем просто суммирование кадров (хотя я не знаю точную логику c), но другой подход может быть создать модель кадра для отслеживания более одного Int:

struct FrameScore {
    let frameNumber: Int
    let firstScore: Int
    let secondScore: Int
    let previousScore: Int

    var frameScore: Int { return self.firstScore + self.secondScore }
    var totalScore: Int { return self.frameScore + self.previousScore }

    var isStrike: Bool { return self.firstScore == 10 }
    var isSpare: Bool { return !self.isStrike && self.frameScore == 10 }
}

А затем основной вид может обновиться, чтобы сохранить список кадров:

struct StartBowlingView: View {

    @State var frames = [FrameScore]()

    var body: some View {
        List{
            ForEach(self.frames, id: \.frameNumber) { frame in
                RowView(title: "\(frame.frameNumber)",
                    framescore: "\(frame.frameScore)",
                    totalscore: "\(frame.totalScore)")
            }

            Button("Add Score") {
                let first = Int.random(in: 0...10)
                let second = Int.random(in: 0...(10 - first))

                // Here's where to add some logic about the prevous frames' strikes and spares affecting the new frame/total score

                self.frames.append(
                    FrameScore(frameNumber: self.frames.count + 1,
                               firstScore: first,
                               secondScore: second,
                               previousScore: self.frames.last?.totalScore ?? 0))
            }
        }
    }
}
...