需求:
输入银行卡号需要四个数字一组,想找个现成没找到,没办法只有自己写了
构思:
需要监听输入框的变化,不断修改输入框的输入文本的格式
实现:
第一步:
在分类中添加格式化字符串代码和移除空格代码
extension String{
/*
*去掉所有空格
*/
var removeAllSapce: String {
return self.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
}
/// 分组格式化
/// - Parameter joined: 间隔字符串
/// - Returns: 格式化好的字符串
public func formateForBankCard(joined: String = " ") -> String {
guard self.count > 0 else {
return self
}
let length: Int = self.count
let count: Int = length / 4
var data: [String] = []
for i in 0..<count {
let start: Int = 4 * i
let end: Int = 4 * (i + 1)
data.append(self[start..<end])
}
if length % 4 > 0 {
data.append(self[4 * count..<length])
}
let result = data.joined(separator: " ")
return result
}
}
使用方式
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textView: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.textView.delegate = self
self.textView.addTarget(self, action: #selector(textChange), for: .editingChanged)
}
@objc func textChange(){
let text = self.textView.text
let tempText = text!.removeAllSapce
self.textView.text = tempText.formateForBankCard()
}
}