Обновить текст кнопки при нажатии на жест - PullRequest
0 голосов
/ 06 апреля 2020

То, что я пытаюсь сделать, это обновить текст метки кнопки при действии или onTapGesture. Но я не могу понять, как получить обратно, чтобы обновить метку кнопки.

Я получаю Значение типа 'ContentView' не имеет члена 'lable' для этого.

Button(action: {}) {
    Text("Enroute")
}.foregroundColor(.red)
.onTapGesture {
    self.lable(Text(getCurrentTime()))
}

И Здесь значение типа 'ContentView' также не имеет члена 'lable' .

Button(action: {
    self.lable(Text(getCurrentTime()))
}) {
    Text("Enroute")
}.foregroundColor(.red)

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        List {
            Button(action: {}) {
                Text("Enroute")
            }.foregroundColor(.red)
            Button(action: {}) {
                Text("On Scene")
            }.foregroundColor(.yellow)
            Button(action: {}) {
                Text("Leave Scene")
            }.foregroundColor(.green)
            Button(action: {}) {
                Text("At Hospital")
            }.foregroundColor(.blue)
            Button(action: {}) {
                Text("In Service")
            }.foregroundColor(.gray)
        }
        .navigationBarTitle("Times")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

func getCurrentTime() -> String {
    let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = "HH:mm:ss"

    return dateFormatter.string(from: Date())
}

1 Ответ

2 голосов
/ 06 апреля 2020

Вам не нужно добавлять onTapGesture к кнопке, кнопка action вызывается при нажатии кнопки.

Для изменения метки вам нужно будет изменить состояние вашего представления, когда кнопка нажата, и свойство body пересчитает просмотры внутри, чтобы отобразить обновленное время.

struct ContentView: View {

    @State var enrouteText = "Enroute"
    @State var onSceneText = "On Scene"

    var body: some View {
        List {
            Button(action: {
                self.enrouteText = getCurrentTime()
            }) {
                Text(enrouteText)
            }
            .foregroundColor(.red)
            Button(action: {
                self.onSceneText = getCurrentTime()
            }) {
                Text(onSceneText)
            }
            .foregroundColor(.yellow)
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...