GetCheckCodeButton.swift 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // GetCheckCodeButton.swift
  3. // fiveConstant
  4. //
  5. // Created by 李建 on 2023/1/14.
  6. //
  7. import SwiftUI
  8. import Combine
  9. struct GetCheckCodeButton: View {
  10. @State var countSecond = 60
  11. @State var isCountStart: Bool = false
  12. @State var timer: Timer?
  13. var act: ()->()?
  14. init(action: @escaping ()->Void){
  15. self.act = action
  16. }
  17. var body: some View {
  18. Button(action: {
  19. self.startTimer()
  20. self.act()
  21. }, label: {
  22. Text(!isCountStart ? "获取验证码" : "\(countSecond)S")
  23. .font(.caption)
  24. .foregroundColor(isCountStart ? Color.gray : Color("MainColor"))
  25. .padding(7)
  26. .frame(width: 80, height: 30)
  27. .overlay(RoundedRectangle(cornerRadius: 50)
  28. .stroke(isCountStart ? Color.gray : Color("MainColor"))
  29. )
  30. }).disabled(isCountStart)
  31. }
  32. func startTimer() {
  33. isCountStart = true
  34. timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { _ in
  35. if countSecond == 0 {
  36. isCountStart = false
  37. countSecond = 60
  38. timer?.invalidate()
  39. timer = nil
  40. }
  41. countSecond -= 1
  42. })
  43. }
  44. }
  45. struct GetCheckCodeButton_Previews: PreviewProvider {
  46. static var previews: some View {
  47. GetCheckCodeButton {
  48. print("1`23")
  49. }
  50. }
  51. }