核心要点
- 如何通过Buttom按钮触发事件来改变Text的显示内容
- Text控件通过onApper绑定函数触发事件
代码
struct ContentView: View {
@State var timeCount:Double = 0.0
@State var checkOut: Int = 0
var timer: Timer {
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
self.timeCount += 0.1
}
}
func timeString(time: Double) -> String {
return String(format: "%.1f", time)
}
var body: some View {
HStack {
Text(timeString(time:self.timeCount)).onAppear{
_ = self.timer
}
Button(action: {
self.timeCount += 1.0
}) {
Text("Check")
}
}
}
}
逻辑分析
- 首先声明两个变量timeCount和chectOut分别来计算时间和点击按钮的次数;
- 调用Timer.scheduledTimer()方法来实现时间调度功能,这里我们设置每个0.1触发一次累加功能;
- 添加Text和Button控件;
- 在Text控件中,现实的内容为timeString函数的返回值,onApper方法的作用是在Text控件开始的时候触发;
- 在onApper方法中,放置了self.timer方法,这样就实现了动态更新Text控件显示内容的功能;
- 在Button控件中的action参数里,添加self.timeCount += 1.0,实现了点击Button后动态更新Text显示内容的功能
欢迎关注我的公众号,回复关键字“大礼包” ,将会有大礼相送!!! 祝各位面试成功!!!