views:

322

answers:

1

I'd like to create a UITextView that you can tap anywhere within it and start typing at that location. The default behavior of the control is that typing starts where the last character ended. So, if I had a UITextView with no text in it and tap in the middle of the control, I'd like typing to start there--not in the upper left.

What is the best way to implement this behavior? I've considered making the default text value of the view to be 3000 space characters or something similar, but this seems like not an elegant solution. Suggestions?

+2  A: 

I suggest deriving from UITextView to create a custom view that handles taps. You'll want to override the following methods, probably:

  • touchesBegan:withEvent
  • touchesMoved:withEvent
  • touchesEnded:withEvent
  • touchesCancelled:withEvent

Make sure the userInteractionEnabled property has a default value of YES. Override hitTest:withEvent and pointInside:withEvent to figure out where in your view the user tapped.

Be sure and read the Responding to Events section in the View Programming Guide for iOS, and also see the Event Handling Guide for iOS for more details.

Anyway, once you figure out where the user touched, you can modify the text or reposition the karat as appropriate.

Ben Collins
I'll give this a try and see how it goes. I've tried many times to deal with touch events on a UITextView and it generally does not go well because of the way it tends to eat touch events. I've never tried using the hit tests though.
Harkonian