Swift - 图形验证码 (含OC版本链接)

前言:
把OC版本用swift翻译了一遍,如果有什么语法可以优化的,或者什么问题可以提出,互相交流,谢谢!

目录:

一、样例

二、Swift代码

三、OC版本代码链接

样例:


直接上代码:

 import UIKit
 
 // MARK: 基本的样式
 struct CaptchaViewStytel {
     
     /// 随机颜色
     var kRandomColor:UIColor{
         return UIColor.init(red: CGFloat(Float(arc4random()%255)/255.0), green: CGFloat(Float(arc4random()%255)/255.0), blue: CGFloat(Float(arc4random()%255)/255.0), alpha: 1.0)
     }
     /// 线数量
     var kLineCount = 6
     /// 线宽
     var kLineWidth = 1.0
     /// 字符数量
     var kCharCount = 4
     /// 随机字体大小
     var kFontSize:UIFont?{
         return UIFont.systemFont(ofSize: CGFloat(Float(arc4random()%5) + 18))
     }
 }
 
 
 class CaptchaView: UIView {
 
     /// 字符素材数组
     var changeArray: NSArray?
     /// 验证码的字符串
     var changeString: String?
     /// 基本样式
     var stytel:CaptchaViewStytel!
     
     override init(frame: CGRect) {
         super.init(frame: frame)
         
         // 初始化
         self.setUpUI()
         // 显示一个随机验证码
         self.changeCaptcha()
         
     }
     
     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
     
     
     // MARK: 初始化
     func setUpUI() -> Void {
        
       let stytel = CaptchaViewStytel()
       self.stytel = stytel
         
       self.backgroundColor = stytel.kRandomColor
        
       //设置layer圆角半径
       //self.layer.cornerRadius = 5.0
       //隐藏边界
       //self.layer.masksToBounds = true
         
     }
     
      // MARK: 布局约束
     override func layoutSubviews() {
         super.layoutSubviews()
     }
     
     override func touchesBegan(_ touches: Set, with event: UIEvent?) {
         self.backgroundColor = stytel.kRandomColor
        
         //点击界面,切换验证码
         self.changeCaptcha()
         
         //setNeedsDisplay调用drawRect方法来实现view的绘制
         self.setNeedsDisplay()
     }
     
     
    // MARK: 显示一个随机验证码
     func changeCaptcha(){
       
         // 从字符数组中随机抽取相应数量的字符,组成验证码字符串
         // 数组中存放的是全部可选的字符,可以是字母,也可以是中文
         let changeArray = ["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"]
         self.changeArray = changeArray as NSArray
         self.changeString = String()
         
         // 随机从数组中选取需要个数的字符,然后拼接为一个字符串
         for _  in 0..

OC版本链接: iOS 生成本地验证码以及使用

你可能感兴趣的:(Swift - 图形验证码 (含OC版本链接))