Home>

I want to display the string that is always at the end of the TextView. I want to always put the cursor position before the fixed character when the editing of TextView is started.

I tried to move the cursor by referring to the link below, but it didn't work.
I would be grateful if you could teach me a good way.

Referenced articles

The output in DidBeginEditing shows 0, but the cursor hasn't moved.

func textViewShouldBeginEditing (_ textView: UITextView)->Bool {
        if let selectedRange = textView.selectedTextRange {
            textView.selectedRange.location = 0
            let cursorPosition = textView.offset (from: textView.beginningOfDocument, to: selectedRange.start)
            print (cursorPosition)
        }
        return true
    }
func textViewDidBeginEditing (_ textView: UITextView) {
        if let selectedRange = textView.selectedTextRange {
            textView.selectedRange.location = 0
            let cursorPosition = textView.offset (from: textView.beginningOfDocument, to: selectedRange.start)
            print (cursorPosition)
        }
    }
  • Answer # 1

    To get the current position of the cursor dynamicallytextViewDidChangeSelection (_ :)Is likely to be used, so for example

      var suffix = "[this is a fixed character]"
        override func viewDidLoad () {
            super.viewDidLoad ()
            textView.delegate = self
            textView.text = suffix
        }
        func textViewDidChangeSelection (_ textView: UITextView) {
            if let selectedRange = textView.selectedTextRange {
                let cursorPosition = textView.offset (from: textView.beginningOfDocument, to: selectedRange.start)
                if textView.text.count --suffixPosition<suffix.count {
                    // Fix the cursor just before the fixed character
                    textView.selectedRange.location = textView.text.count --suffix.count
                }
            }
        }

    If it looks like this, the cursor will not go to the right of the beginning of the fixed character.

Related articles