(Swift) Generate random verification code

created at 11-14-2021 views: 1

1) Usage scenario

  • Mostly used for card script verification;
  • Support background color;
  • Support random angle;
  • The effect is as follows;

verification code

2) How to use

4 lines of code can be introduced and used;

let reView = CCRandomCodeView()
// reView.backgroundColor = .purple
view.addSubview(reView)
reView.changeBlock = { res in }
reView.snp.makeConstraints { make in
  make.center.equalToSuperview()
  make.size.equalTo(CGSize(width: 100, height: 30))
}

3) source code sharing

//
//  CCRandomCodeView.swift
//  HelloSwift
//
//  Created by well on 2021/9/24.
//

import UIKit

class CCRandomCodeView: UIView {

/// Number of verification codes (default 4)
     private let defaultCount: Int = 4
     /// Result string
     private var resString: String = ""
     /// Verification code data source
     private var codeArray = [String]()
     /// Angle data source
     private var angleArray = [Double]()
     /// Result label
     private var labelArray = [UILabel]()
     /// Constraint layout stackView
     private var stackView: UIStackView!
     /// Result callback
     public var changeBlock: ((String) -> Void)?

     required init?(coder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }

     // MARK:-Deinitializer
     deinit {print("CCRandomCodeView deinit!")}

     // MARK:-initializer
     override init(frame: CGRect) {
         super.init(frame: .zero)
         self.initData()
         self.setUI()
     }

    // MARK:-Data initialization
    func initData()  {
        angleArray = [0, 0.25, 0.5, 0.75, 1]
        codeArray = ["0","1","2","3","4","5","6","7","8","9",
                     "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
                     "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
        for _ in 0..<defaultCount { labelArray.append(createLabel()) }
    }

    // MARK: - UI初始化
    func setUI() {
        self.layer.masksToBounds = true
        stackView = UIStackView(arrangedSubviews: labelArray)
        stackView.alignment = .fill
        stackView.axis = .horizontal
        stackView.distribution = .equalCentering
        self.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    override func layoutSubviews() {
        for _ in 0...9 {
            let path = UIBezierPath()
            let pX = arc4random_uniform(UInt32(self.frame.width))
            let pY = arc4random_uniform(UInt32(self.frame.height))
            path.move(to: CGPoint(x: CGFloat(pX), y: CGFloat(pY)))
            let ptX = arc4random_uniform(UInt32(self.frame.width))
            let ptY = arc4random_uniform(UInt32(self.frame.height))
            path.addLine(to: CGPoint(x: CGFloat(ptX), y: CGFloat(ptY)))

            let layer = CAShapeLayer()
            layer.strokeColor = UIColor.hexColor("#ffffff", 0.2).cgColor
            layer.lineWidth = 1
            layer.strokeEnd = 1
            layer.fillColor = UIColor.clear.cgColor
            layer.path = path.cgPath
            stackView.layer.addSublayer(layer)
        }
        changeValue()
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { changeValue() }

    // MARK:-private method
        private func changeValue() {
            // First empty, then update
            resString = ""
            self.backgroundColor = .random
            for (_, ele) in labelArray.enumerated() {
                let aIndex = Int(arc4random_uniform(UInt32(angleArray.count)))
                let cIndex = Int(arc4random_uniform(UInt32(codeArray.count)))
                let textString = codeArray[cIndex]
                let angleValue = angleArray[aIndex]
                resString.append(textString)

                ele.text = textString
                ele.transform = CGAffineTransform(rotationAngle: angleValue)
            }
            changeBlock?(resString)
        }

        private func createLabel() -> UILabel {
            let l = UILabel()
            l.textColor = .black
            l.font = RegularFont(16)
            l.textAlignment = .center
            return l
        }
}
created at:11-14-2021
edited at: 11-14-2021: