SwiftUI 学习笔记 01 - PlusOneSecond

核心要点

  1. 如何通过Buttom按钮触发事件来改变Text的显示内容
  2. 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")
            }
        }
        
    }
}

逻辑分析

  1. 首先声明两个变量timeCount和chectOut分别来计算时间和点击按钮的次数;
  2. 调用Timer.scheduledTimer()方法来实现时间调度功能,这里我们设置每个0.1触发一次累加功能;
  3. 添加Text和Button控件;
  4. 在Text控件中,现实的内容为timeString函数的返回值,onApper方法的作用是在Text控件开始的时候触发;
  5. 在onApper方法中,放置了self.timer方法,这样就实现了动态更新Text控件显示内容的功能;
  6. 在Button控件中的action参数里,添加self.timeCount += 1.0,实现了点击Button后动态更新Text显示内容的功能

欢迎关注我的公众号,回复关键字“大礼包” ,将会有大礼相送!!! 祝各位面试成功!!!

发布了112 篇原创文章 · 获赞 2 · 访问量 5550

猜你喜欢

转载自blog.csdn.net/weixin_41818794/article/details/104492542
今日推荐