Home > Software design >  TextField i.e. showing % during text input
TextField i.e. showing % during text input

Time:03-30

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.

CodePudding user response:

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.

CodePudding user response:

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)
        }
    }

  • Related