SwiftUI通过.onReceive使用Combine的方式,它需要一个发布者。您可以将可观察对象作为属性公开发布者
我们的timer正好是一个发布者

struct VerificationPage: View {
    @State var countDown:Int = 60
        var body: some View {
                    Button(action: {
                        self.countDown = 60
                    }, label: {
                        if self.countDown != 0{
                            Text("\(self.countDown)s")
                                .foregroundColor(.white)
                                //这里直接将Timer作为发送者every是每隔一秒
                                .onReceive(Timer.publish(every: 1, on: .main, in: .common).autoconnect(), perform: { _ in
                                //不等于零每隔一秒减一
                                    if (self.countDown != 0) {
                                        self.countDown -= 1
                                    }
                                })
                    
                        }else{
                            Text("获取验证码")
                                .font(.system(size: 14))
                                .foregroundColor(.white)
                        }
                        
                    })
        }
     }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐