gpt4 book ai didi

ios - 将 UITextField MM/YY 格式化为过期时间

转载 作者:搜寻专家 更新时间:2023-11-01 06:27:46 26 4
gpt4 key购买 nike

尝试为信用卡到期日设置一个 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
}
}

最佳答案

Swift 5 :

这是验证输入的月份和年份的解决方案

使用 TextField 委托(delegate)方法 shouldChangeCharactersIn

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let oldText = textField.text, let r = Range(range, in: oldText) else {
return true
}
let updatedText = oldText.replacingCharacters(in: r, with: string)

if string == "" {
if updatedText.count == 2 {
textField.text = "\(updatedText.prefix(1))"
return false
}
} else if updatedText.count == 1 {
if updatedText > "1" {
return false
}
} else if updatedText.count == 2 {
if updatedText <= "12" { //Prevent user to not enter month more than 12
textField.text = "\(updatedText)/" //This will add "/" when user enters 2nd digit of month
}
return false
} else if updatedText.count == 5 {
self.expDateValidation(dateStr: updatedText)
} else if updatedText.count > 5 {
return false
}

return true
}

下面函数中的验证逻辑

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 enteredYear = Int(dateStr.suffix(2)) ?? 0 // get last two digit from entered string as year
let enteredMonth = Int(dateStr.prefix(2)) ?? 0 // get first two digit from entered string as month
print(dateStr) // This is MM/YY Entered by user

if enteredYear > currentYear {
if (1 ... 12).contains(enteredMonth) {
print("Entered Date Is Right")
} else {
print("Entered Date Is Wrong")
}
} else if currentYear == enteredYear {
if enteredMonth >= currentMonth {
if (1 ... 12).contains(enteredMonth) {
print("Entered Date Is Right")
} else {
print("Entered Date Is Wrong")
}
} else {
print("Entered Date Is Wrong")
}
} else {
print("Entered Date Is Wrong")
}

}

关于ios - 将 UITextField MM/YY 格式化为过期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51631530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com