前面的文章里面有关于自定义验证码视图OC相关的代码,在swift_3中,大体上的结构都是相同的,只是因为swift是强类型语言,所以在局部上可能有所不同。
首先还是继承于UIButton
class VerifyCodeButton: UIButton {
}
构建视图主要是重写视图的绘制
//重绘
override func draw(_ rect: CGRect)
重绘主要包括干扰线的绘制和验证码字符的绘制
干扰线的绘制
let context = UIGraphicsGetCurrentContext()
context!.setLineWidth(CGFloat(kLineWith));
for _ in 0..<kLineCount {
let randomCorlor = UIColor.init(colorLiteralRed: Float(arc4random()%255)/Float(255.0), green: Float(arc4random()%255)/Float(255.0), blue: Float(arc4random()%255)/Float(255.0), alpha: 1.0)
context?.setStrokeColor(randomCorlor.cgColor)
//起点
pX = CGFloat(arc4random()%UInt32(rect.size.width))
pY = CGFloat(arc4random()%UInt32(rect.size.height))
context?.move(to: CGPoint(x: pX!, y: pY!))
//终点
pX = CGFloat(arc4random()%UInt32(rect.size.width))
pY = CGFloat(arc4random()%UInt32(rect.size.height))
context?.addLine(to: CGPoint(x: pX!, y: pY!))
context?.strokePath();
}
验证码的视图绘制
for index in 0..<self.verifyCode.characters.count {
pX = CGFloat(Int(arc4random()) % width) + (rect.size.width+4)/CGFloat(counts) * CGFloat(index)
pY = CGFloat(arc4random()%UInt32(hight))
point = CGPoint(x: pX!, y: pY!)
let c = self.verifyCode[self.verifyCode.index(self.verifyCode.startIndex, offsetBy: index)]
let textC :String = "\(c)"
let randomFont = UIFont.systemFont(ofSize:CGFloat(arc4random()%5+15))
textC.draw(at: point!, withAttributes: [NSFontAttributeName:randomFont])
}
遇到的小坑
使用"()"构建的字符串和format构建的字符串,在characters.count上市不同的