滴滴的驗證碼框看著很帥锡凝,用起來很舒服贰剥,所以就仿寫了一個 :)
實現(xiàn)思路其實很簡單,就是4個 UITextField 鸳吸,設(shè)置成框框樣式熏挎,然后監(jiān)聽輸入和鍵盤,最后通過代理傳值~
0.創(chuàng)建 UITextField 很多重復(fù)代碼晌砾,就封裝一個創(chuàng)建函數(shù)來減少重復(fù)代碼
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.循環(huán)創(chuàng)建 UITextField 數(shù)組
// 創(chuàng)建 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.監(jiān)聽每一個 UITextField 值的變化婆瓜,切換輸入框
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if !textField.hasText {
// tag 對應(yīng)數(shù)組下標(biāo)
let index = textField.tag
textField.resignFirstResponder()
if index == numOfRect - 1 {
textfieldarray[index].text = string
// 拼接結(jié)果
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.監(jiān)聽鍵盤刪除鍵:這個我用的方式可能比較奇怪,我重寫了 UITextField 里的 deleteBackward (就是簡單的加了個代理回調(diào)進(jìn)去)
func didClickBackWard() {
for i in 1..<numOfRect{
if !textfieldarray[i].isFirstResponder {
continue
}
textfieldarray[i].resignFirstResponder()
textfieldarray[i-1].becomeFirstResponder()
textfieldarray[i-1].text = ""
}
}
附上監(jiān)聽鍵盤刪除鍵方法
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 啊~么么噠~