尝试设置textField
作为信用卡的有效期,以下代码仅在试图更改行为时正常工作,当前您在输入第三个数字 / 字符时会添加为过期格式。如果我想在用户键入第二个数字后添加 / 字符怎么办,例如,如果用户键入01,则直接插入分隔符
open func reformatAsExpiration(_ textField: UITextField) {
guard let string = textField.text else { return }
let expirationString = String(ccrow.expirationSeparator)
let cleanString = string.replacingOccurrences(of: expirationString, with: "", options: .literal, range: nil)
if cleanString.length >= 3 {
let monthString = cleanString[Range(0...1)]
var yearString: String
if cleanString.length == 3 {
yearString = cleanString[2]
} else {
yearString = cleanString[Range(2...3)]
}
textField.text = monthString + expirationString + yearString
} else {
textField.text = cleanString
}
}
答案 0 :(得分:1)
在您的文本字段中使用此代码确实开始对该文本字段进行编辑。
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = .date
datePickerView.addTarget(self, action: #selector(handleChange(sender:)), for: .valueChanged)
yourTextField.inputView = datePickerView
现在实现此方法以在选择器视图中更改句柄
@objc func handleChange(sender: UIDatePicker){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
yourTextfield.text = dateFormatter.string(from: sender.date)
}
希望它会有所帮助:)
答案 1 :(得分:1)
var cleanString = string.replacingOccurrences(of:“ /”,带有:“”)
if cleanString.rangeOfCharacter(from: unsupportedCharacterSet) != nil {
return ""
}
let dateString: String
if cleanString.count == 0 {
return string
} else if cleanString.count > 4 {
// trim the string down to 4
let reqIndex = cleanString.index(cleanString.startIndex, offsetBy: 4)
cleanString = String(cleanString[..<reqIndex])
}
if cleanString.hasPrefix("0") == false && cleanString.hasPrefix("1") == false {
dateString = "0" + cleanString
} else {
dateString = cleanString
}
let currentYear = Calendar.current.component(.year, from: Date()) % 100 // This will give you current year (i.e. if 2019 then it will be 19)
let currentMonth = Calendar.current.component(.month, from: Date()) // This will give you current month (i.e if June then it will be 6)
var newText = ""
for (index, character) in dateString.enumerated() {
print("index: \(index)")
if index == 1 {
let enterdMonth = Int(dateString.prefix(2)) ?? 0 // get first two digit from entered string as month
print("enterdMonth at 1:\(enterdMonth)")
if (1 ... 12).contains(enterdMonth){
if enterdMonth < 10 {
newText = "0" + "\(enterdMonth)" + "/"
}else {
newText = "\(enterdMonth)" + "/"
}
}else{
}
}else if index == 2 {
if (2 ... 99).contains(Int(String(character))!) { // Entered year should be greater than 2019.
newText.append(character)
}else{
}
}else if index == 3 {
print("index---: \(index)")
let enterdYr = Int(dateString.suffix(2)) ?? 0 // get last two digit from entered string as year
let enterdMonth = Int(dateString.prefix(2)) ?? 0 // get first two digit from entered string as month
print("enterdYr: \(enterdYr)")
print("currentYear: \(currentYear)")
if (2 ... 99).contains(enterdYr) { // Entered year should be greater than 2019
if enterdYr >= currentYear {
if (1 ... 12).contains(enterdMonth) {
if enterdMonth < 10 {
newText = "0" + "\(enterdMonth)" + "/" + "\(enterdYr)"
}else {
newText = "\(enterdMonth)" + "/" + "\(enterdYr)"
}
return newText
}
}
}
}
else {
newText.append(character)
}
}
return newText
}
答案 2 :(得分:0)
您可以使用文本字段委托方法shouldChangeCharactersIn
来完成
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string == "" {
return true
}
let currentText = textField.text! as NSString
let updatedText = currentText.replacingCharacters(in: range, with: string)
textField.text = updatedText
let numberOfCharacters = updatedText.count
if numberOfCharacters == 2 {
textField.text?.append("/")
}
return false
}
答案 3 :(得分:0)
迅速5:
这是验证输入的月份和年份的解决方案
使用TextField委托方法shouldChangeCharactersIn
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentText = textField.text! as NSString
let updatedText = currentText.replacingCharacters(in: range, with: string)
if string == "" {
if textField.text?.count == 3
{
textField.text = "\(updatedText.prefix(1))"
return false
}
return true
}
if updatedText.count == 5
{
expDateValidation(dateStr:updatedText)
return updatedText.count <= 5
} else if updatedText.count > 5
{
return updatedText.count <= 5
} else if updatedText.count == 1{
if updatedText > "1"{
return updatedText.count < 1
}
} else if updatedText.count == 2{ //Prevent user to not enter month more than 12
if updatedText > "12"{
return updatedText.count < 2
}
}
textField.text = updatedText
if updatedText.count == 2 {
textField.text = "\(updatedText)/" //This will add "/" when user enters 2nd digit of month
}
return false
}
以下功能中的验证逻辑
func expDateValidation(dateStr:String) {
let currentYear = Calendar.current.component(.year, from: Date()) % 100 // This will give you current year (i.e. if 2019 then it will be 19)
let currentMonth = Calendar.current.component(.month, from: Date()) // This will give you current month (i.e if June then it will be 6)
let enterdYr = Int(dateStr.suffix(2)) ?? 0 // get last two digit from entered string as year
let enterdMonth = Int(dateStr.prefix(2)) ?? 0 // get first two digit from entered string as month
print(dateStr) // This is MM/YY Entered by user
if enterdYr > currentYear
{
if (1 ... 12).contains(enterdMonth){
print("Entered Date Is Right")
} else
{
print("Entered Date Is Wrong")
}
} else if currentYear == enterdYr {
if enterdMonth >= currentMonth
{
if (1 ... 12).contains(enterdMonth) {
print("Entered Date Is Right")
} else
{
print("Entered Date Is Wrong")
}
} else {
print("Entered Date Is Wrong")
}
} else
{
print("Entered Date Is Wrong")
}
}
答案 4 :(得分:0)
迅速5解决方案以格式化日期mm / yy:
首先,我添加了一个观察者来检查文本更改:
dateTextField.addTarget(self, action: #selector(expirationDateDidChange), for: .editingChanged)
这是实时格式化文本的功能:
@objc func expirationDateDidChange() {
let currentText = dateTextField.text ?? ""
// To remove " / " when user deletes the space after '/'
if currentText.count == 4 {
dateTextField.text = String(currentText.prefix(2))
return
}
var dateText = dateTextField.text?.replacingOccurrences(of: "/", with: "") ?? ""
dateText = dateText.replacingOccurrences(of: " ", with: "")
var newText = ""
for (index, character) in dateText.enumerated() {
if index == 1 {
newText = "\(newText)\(character) / "
} else {
newText.append(character)
}
}
dateTextField.text = newText
}