点击手势上的更新按钮文本

时间:2020-04-05 23:55:10

标签: swiftui

我想做的是在action或onTapGesture上更新按钮标签的文本。但是我不知道如何从后面更新按钮的标签。

我得到“ ContentView”类型的值与此成员没有成员“标签”

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

并且“ ContentView”类型的值在这里也没有成员“标签”

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 个答案:

答案 0 :(得分:3)

您无需在按钮上添加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)
        }
    }
}