如何在swift中为文本字段设置掩码?例如,当用户键入其显示时的电话文本字段,如目标-C中的此代码的电话格式:
self.textField.mask = @"(##)####-####";
答案 0 :(得分:3)
Swift 4非常简单并且具有Masking Max文本字段长度和Handle Back Space
//MARK: - text field masking
internal func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//MARK:- If Delete button click
let char = string.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) {
print("Backspace was pressed")
textField.text!.removeLast()
return false
}
if textField == txtworkphone
{
if (textField.text?.count)! == 3
{
textField.text = "(\(textField.text!)) " //There we are ading () and space two things
}
else if (textField.text?.count)! == 9
{
textField.text = "\(textField.text!)-" //there we are ading - in textfield
}
else if (textField.text?.count)! > 13
{
return false
}
}
}
答案 1 :(得分:2)
快速4 && 5简易电话号码掩码
func formattedNumber(number: String) -> String {
let cleanPhoneNumber = number.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
let mask = "## ### ###"
var result = ""
var index = cleanPhoneNumber.startIndex
for ch in mask! where index < cleanPhoneNumber.endIndex {
if ch == "#" {
result.append(cleanPhoneNumber[index])
index = cleanPhoneNumber.index(after: index)
} else {
result.append(ch)
}
}
return result
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return false }
let newString = (text as NSString).replacingCharacters(in: range, with: string)
textField.text = formattedNumber(number: newString)
return false
}