rollingcodes
rollingcodes

Reputation: 16062

UITextInput: How Do I Show the Caret for a Custom UIView That Implements the UITextInput Protocol?

I notice in Apple's UITextInput protocol there is a required method called (CGRect)caretRectForPosition:(UITextPosition *)position that, as you can see, returns a CGRect. When I put a breakpoint inside of the method, it appears the method is never called even when I call the setSelectedTextRange: method. Do I have to implement my own caret object inside the text view? I thought the protocol automatically handled this and just added the caret into the text view with the frame specified by the CGRect returned by caretRectForTextPosition:. How would I go about showing/adding a caret to my UIView class that implements the UITextInput protocol?

EDIT

I have read the documentation all up and down with no results and even searched for example implementations by other people. I eventually just implemented the caret myself. Is that the right/suggested way to even do this?

Upvotes: 1

Views: 1299

Answers (2)

John Shimmin
John Shimmin

Reputation: 31

I found this thread looking for an answer to this question 9 years later. Modern answer: if you've implemented the UITextInput protocol properly (including caretRectForPosition) and attach a UITextInteraction, e.g. from the containing view:

let textInteraction = UITextInteraction(for: .editable)
textInteraction.textInput = self
addInteraction(textInteraction)

then UITextInteraction will handle the cursor display.

Upvotes: 3

Ser Pounce
Ser Pounce

Reputation: 14571

Yes, you do have to implement the caret yourself. See Apple's SimpleTextInput example.

Upvotes: 1

Related Questions