【问题标题】:Update Button Text on Tap Gesture更新点击手势上的按钮文本
【发布时间】:2020-04-06 09:45:56
【问题描述】:

我正在尝试做的是更新按钮标签的操作或 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())
}

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    您不需要将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)
            }
        }
    }
    

    【讨论】:

    • 非常感谢你的洞察力,这让我更接近,@Natalia Panferova;我仍然希望文本默认为“Enroute”或其他任何内容,并且只有在我点击该按钮以显示当前时间后才会更新。幸运的是,我仍然可以通过我的 PPE 与我的手表互动,所以我想用它来标记我正在执行任务的时间,这样当我需要写病人护理报告时,我可以将时间安全地放在某个地方。
    • 我为每个按钮添加了一个状态,我只是在按下它时更新状态。大声笑,非常感谢您的见解!
    • @MarkTomlin 当然,我已经用 2 个按钮和其中的默认文本更新了我的示例,这是您想要实现的更多吗?
    • 完美,这正是我想要的,非常感谢!
    猜你喜欢
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 2014-01-18
    • 2017-07-13
    • 1970-01-01
    • 2020-05-16
    相关资源
    最近更新 更多