ios、swift、swfitUI发送验证码倒计时onReceive接收自定义事件

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)
                        }
                        
                    })
        }
     }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值