【问题标题】:How can I hide middle characters on TextField [closed]如何在 TextField 上隐藏中间字符 [关闭]
【发布时间】:2020-06-04 12:13:06
【问题描述】:

将输入一个 11 个字符的数字,这 11 个字符的中间字符将被隐藏。我该怎么做?

【问题讨论】:

    标签: swift xcode delegates textfield


    【解决方案1】:

    其中一种解决方案是使用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"
    

    【讨论】:

    【解决方案2】:

    你需要实现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
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 2013-05-05
      相关资源
      最近更新 更多