iosswiftuitextviewformatter

iOS Swift - How to add a uneditable suffix to a UITextView


How do I programmatically add a suffix ("kr") to an UITextView?

Thanks!


Solution

  • I assume this is when the user is typing to indicate a currency value.

    In viewDidLoad assign your textview delegate (or wherever you wish to assign the delegate):

    override func viewDidLoad() {
        super.viewDidLoad()
        myTextView.delegate = self
    }
    

    And then to add the suffix to the textview when user is typing

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    
        if string.characters.count > 0 {
            amountTypedString += string
            let newString = amountTypedString + "kr"
            myTextView.text = newString
        } else {
            amountTypedString = String(amountTypedString.characters.dropLast())
            if amountTypedString.characters.count > 0 {
                let newString = amountTypedString + "kr"
                myTextView.text = newString
            } else {
                myTextView.text = "0kr"
            }
        }
        return false
    }