How to set letter spacing of UITextField

前端 未结 7 906
[愿得一人]
[愿得一人] 2021-01-30 12:55

I have an app in which the user has to type a four digit pin code. All digits have to be at a set distance from each other.

Is there a way to do this if the PinTex

相关标签:
7条回答
  • 2021-01-30 13:37

    Need to count the kern for each character and remove it for the last character. There is example on Swift 5.3

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let maxLength = 6
        let symbolWidth = CGFloat(43)
        let font = UIFont.systemFont(ofSize: 30)
        
        if string == "" { // when user remove text
            return true
        }
            
        if textField.text!.count + string.count - range.length > maxLength { // when user type extra text
            return false
        }
        
        let currentText = NSMutableAttributedString(attributedString: textField.attributedText ?? NSMutableAttributedString())
        currentText.deleteCharacters(in: range) // delete selected text
        var newStringLength = 0 
        
        for char in string{
            let newSymbol = NSMutableAttributedString(string: String(char))
            newSymbol.addAttribute(.font, value: font, range: NSMakeRange(0, 1))
            let currentSymbolWidth = newSymbol.size().width
            let kern = symbolWidth - currentSymbolWidth
            newSymbol.addAttribute(.kern, value: kern, range: NSMakeRange(0,1))
            
            currentText.insert(newSymbol, at: range.location + newStringLength)
            newStringLength += 1
        }
        
        if currentText.length == maxLength{
            currentText.addAttribute(.kern, value: 0, range: NSMakeRange(maxLength - 1, 1))
        }
        
        textField.attributedText = currentText
        
        return false
    
    }
    
    0 讨论(0)
提交回复
热议问题