0

how to append % sign after input


extension ViewController: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let currentText = textField.text! as NSString
        let newText = currentText.replacingCharacters(in: range, with: string)
        if newText.hasSuffix("%"){
            textField.text = newText
        }else{
            textField.text = "\(newText) %"
            
        }
        return true
    }
}

This is the rers

as in the picture i just want 1 % sign after the numbers.

Wahid Tariq
  • 159
  • 10
  • Does this answer your question? [Percentage mask for textfield in Swift](https://stackoverflow.com/questions/35770130/percentage-mask-for-textfield-in-swift) – Hammer Class Mar 30 '22 at 06:41
  • your this code `textField.text = "\(newText) %"` is adding % only every key tap... Remove % from your text – Kudos Mar 30 '22 at 06:50
  • that is not the answer of my question, and if i remove % symbol then how i can show % during text input – Wahid Tariq Mar 30 '22 at 06:57

2 Answers2

0

https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619599-textfield says:

Return Value: true if the specified text range should be replaced; otherwise, false to keep the old text.

probably because you return true swift updates with the old text replacing the text property of the text-field you just set. Try returning false as this 'keeps the old text' which is already updated by your code.

Lex
  • 166
  • 1
  • 5
0

The reason is func shouldChangeCharactersIn call before the text is input so it is wrong. What we want in here is after the value changed, add % at the end if not have. Here is the code for do that.

// add action for value change recognized
textField.addTarget(self, action: #selector(didChangeValueTextField(textField:)), for: .editingChanged)


@objc final private func didChangeValueTextField(textField: UITextField)
    {
        let text = textField.text ?? ""
        
        if !text.hasSuffix("%") {
            textField.text! = text + "%"
            
            // make cursor position to be left 1 index because final index is %
            let newPosition = textField.position(from: textField.endOfDocument, offset: -1)!
            textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
        }
    }

Thang Phi
  • 1,641
  • 2
  • 7
  • 16