如何隐藏 TextField 上的中间字符
How can I hide middle characters on TextField
将输入一个11个字符的数字,隐藏这11个字符的中间字符。我该怎么做?
其中一种解决方案是使用 replacingCharacters
方法:
var someStr = "12345678901"
func replaceMiddle(of text: String, withCharacter character: String, offset: Int) -> String {
let i1: String.Index = text.index(text.startIndex, offsetBy: offset)
let i2: String.Index = text.index(text.endIndex, offsetBy: -1 * offset)
let replacement = String(repeating: character, count: text.count - 2 * offset)
return text.replacingCharacters(in: i1..<i2, with: replacement)
}
print(replaceMiddle(of: someStr, withCharacter: "*", offset: 3))
// prints "123*****901"
您需要实现UITextFieldDelegate
,然后您可以使用@pawello2222 生成替换字符串
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var newText = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string)
if NEED_TO_CHANGE_STRING {
textField.text = NEW_STRING
return false // Return false to prevent the UITextField to add the new changes since you have just overriten them
}
return true // Return true will make the UITextField update automatically
}
将输入一个11个字符的数字,隐藏这11个字符的中间字符。我该怎么做?
其中一种解决方案是使用 replacingCharacters
方法:
var someStr = "12345678901"
func replaceMiddle(of text: String, withCharacter character: String, offset: Int) -> String {
let i1: String.Index = text.index(text.startIndex, offsetBy: offset)
let i2: String.Index = text.index(text.endIndex, offsetBy: -1 * offset)
let replacement = String(repeating: character, count: text.count - 2 * offset)
return text.replacingCharacters(in: i1..<i2, with: replacement)
}
print(replaceMiddle(of: someStr, withCharacter: "*", offset: 3))
// prints "123*****901"
您需要实现UITextFieldDelegate
,然后您可以使用@pawello2222 生成替换字符串
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var newText = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string)
if NEED_TO_CHANGE_STRING {
textField.text = NEW_STRING
return false // Return false to prevent the UITextField to add the new changes since you have just overriten them
}
return true // Return true will make the UITextField update automatically
}