滴滴的验证码框看着很帅,用起来很舒服,所以就仿写了一个 :)
实现思路其实很简单,就是4个 UITextField ,设置成框框样式,然后监听输入和键盘,最后通过代理传值~
0.创建 UITextField 很多重复代码,就封装一个创建函数来减少重复代码
private func createTextField(frame:CGRect)->UITextField{
let tv = SwiftyTextField(frame: frame)
tv.borderStyle = .line
tv.textAlignment = .center
tv.font = UIFont.boldSystemFont(ofSize: 40)
tv.textColor = UIColor.init(red: 51/255, green: 51/255, blue: 51/255, alpha: 1)
tv.delegate = self
tv.deleteDelegate = self
addSubview(tv)
tv.keyboardType = .numberPad
return tv
}
1.循环创建 UITextField 数组
// 创建 n个 UITextFiedl
for i in 0..<numOfRect{
let rect = CGRect(x: leftmargin + CGFloat(i)*width + CGFloat(i)*margin, y: 10, width: width, height: width)
let tv = createTextField(frame: rect)
tv.tag = i
textfieldarray.append(tv)
}
2.监听每一个 UITextField 值的变化,切换输入框
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if !textField.hasText {
// tag 对应数组下标
let index = textField.tag
textField.resignFirstResponder()
if index == numOfRect - 1 {
textfieldarray[index].text = string
// 拼接结果
var code = ""
for tv in textfieldarray{
code += tv.text ?? ""
}
delegate?.verificationCodeDidFinishedInput(code: code)
return false
}
textfieldarray[index].text = string
textfieldarray[index + 1].becomeFirstResponder()
}
return false
}
3.监听键盘删除键:这个我用的方式可能比较奇怪,我重写了 UITextField 里的 deleteBackward (就是简单的加了个代理回调进去)
func didClickBackWard() {
for i in 1..<numOfRect{
if !textfieldarray[i].isFirstResponder {
continue
}
textfieldarray[i].resignFirstResponder()
textfieldarray[i-1].becomeFirstResponder()
textfieldarray[i-1].text = ""
}
}
附上监听键盘删除键方法
protocol SwiftyTextFieldDeleteDelegate {
func didClickBackWard()
}
class SwiftyTextField: UITextField {
var deleteDelegate:SwiftyTextFieldDeleteDelegate?
override func deleteBackward() {
super.deleteBackward()
deleteDelegate?.didClickBackWard()
}
}
4.输入完成,代理传值
protocol SwiftyVerificationCodeViewDelegate {
func verificationCodeDidFinishedInput(code:String)
}
效果图
最后来一手完整项目地址:https://github.com/KFCFans/SwiftyVerificationCodeView
求 Star 啊~么么哒~