提问者:小点点

Swift 5-用X掩码文本字段文本


我想实现的是,文本字段的格式应该是XXXX XXXX XXXX当用户点击show按钮时,它应该显示文本1234 5678 9123

请帮帮我

下面是我的代码,在那里我能够实现1234 5678 9123这种格式,屏蔽和存储原始数据是挂起的。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
        if textField.tag == 0 || textField.tag == 1 {
        if string.isBackspace
        {
            if range.location == 5 || range.location == 10
            {
                textField.text?.removeLast()
            }
        }
        
        if string == ""{
            return true
        }

        //range.length will be greater than 0 if user is deleting text - allow it to replace
        if range.length > 0
        {
            return true
        }

        //Don't allow empty strings
        if string == " "
        {
            return false
        }

        //Check for max length including the spacers we added
        if range.location > 13 //23
        {
            return false
        }

        var originalText = textField.text
        let replacementText = string.replacingOccurrences(of: " ", with: "")

        //Verify entered text is a numeric value
        let digits = NSCharacterSet.decimalDigits
        for char in replacementText.unicodeScalars
        {
            if !(digits as NSCharacterSet).longCharacterIsMember(char.value)
            {
                return false
            }
        }
        //Put an empty space after every 4 places
        if (originalText?.count)! > 0
        {
            if (originalText?.count)! < 5 && (originalText?.count)! % 4 == 0{
                originalText?.append(" ")
            }else if(((originalText?.count)! + 1) % 5 == 0){
                originalText?.append(" ")
            }

        }

        textField.text = originalText
        }
        
        //2 - Nick Name,3 - Recipient Name
        if textField.tag == 2 || textField.tag == 3 {
            //Max Limit for Nick Name and Benificiary Name is 65
            if range.location > 64
            {
                return false
            }
        }
        return true
    }

共1个答案

匿名用户

如果我理解正确的话,您的要求是创建一个自定义的安全文本字段。要求是:

  • 用户最多可以输入12个符号
  • 只允许数字
  • 文本字段可能具有“屏蔽”和“普通”模式
  • 显示的文本应通过将4个字符组合在一起来设置格式
  • 每组之间有一个空格
  • 在“屏蔽”模式下,所有数字都被替换为“X”符号
  • 正常模式下数字可见

此外,它会很好,所有的文本字段功能将工作,包括复制粘贴,选择,插入代码在文本中间...

我创建了一个新项目,并很快以以下内容结束:

class ViewController: UIViewController {
    
    @IBOutlet private var textField: UITextField?
    
    private var actualText: String = ""
    private var maskedText: String = ""
    
    private var masked: Bool = true {
        didSet {
            refreshTextField()
        }
    }
    
    @IBAction private func maskedTogglePressed(_ sender: Any) {
        masked = !masked
    }
    
    private func refreshTextField() {
        textField?.text = masked ? maskedText : actualText
    }
}

extension ViewController: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        var newString = (actualText as NSString).replacingCharacters(in: range, with: string) // Apply new text
        
        // Remove all whitespaces
        newString = newString.replacingOccurrences(of: " ", with: "")
        // Remove all that is not a number
        newString = newString.filter("0123456789".contains)
        
        // Split string into components of max 4
        var components: [String] = {
            var toDeplete = newString
            var components: [String] = []
            while !toDeplete.isEmpty {
                let length = min(toDeplete.count, 4)
                components.append(String(toDeplete.prefix(length)))
                toDeplete.removeFirst(length)
            }
            return components
        }()
        // Limit to maximum of 3 components
        if components.count > 3 {
            components = Array(components[0..<3])
        }
        
        // Generate masked components, replacing all characters with X
        let maskedComponents: [String] = components.map { String($0.map { character in return "X" }) }
        
        // Add spaces
        newString = components.joined(separator: " ")
        let maskedText = maskedComponents.joined(separator: " ")
        
        // Assign new strings
        self.actualText = newString
        self.maskedText = maskedText
        
        // Refresh field
        refreshTextField()
        
        // Disallow text field to apply it's change
        return false
    }
    
}

在处理字符串时需要一些改进。但它起作用了。

代码被注释,并且应该提供关于解决方案的更多信息。