3

I have a UITextField and it must blink the cursor anyway, even its userInteractionEnabled property is set to NO. I don't want the UITextField to becomeFirstResponder and show the keyboard.

Now you may be asking:

1. If you want to hide the keyboard, why to show the cursor?

A: The problem is that I need to show the user the UITextField is being edited, with a different/custom keyboard.

2. So why don't you use the inputView property?

A: Because the keyboard in inputView comes up from bottom, and I want my custom keyboard in the center of the screen.

So let's go to the real question:

How can I show the cursor? Is there any property I can set? If not, how I would draw a cursor? Making a UIView that gets added and removed with alpha, or subclassing UITextField and overriding drawInRect?

Community
  • 1
  • 1
Natan R.
  • 5,141
  • 1
  • 31
  • 48

1 Answers1

4

You can add a small UIView with a repeting animation that sets the alpha to 0 and 1 back and forth with animateWithDuration:delay:options:animations:completion:.

[UIView animateWithDuration:1 
                      delay:0 
                    options:UIViewAnimationOptionRepeat 
                 animations:^{ [cursorView setAlpha:0]; }
                 completion:^(BOOL animated){ [cursorView setAlpha:1]; } ];

To position the view correctly as a subview of the textfield, in front of the text entered, you can use the NSString method sizewithfont:forWidth:lineBreakMode:

andreamazz
  • 4,256
  • 1
  • 20
  • 36
  • Wow, didn't know about `UIViewAnimationOptionRepeat`. I'll try that! – Natan R. Aug 26 '12 at 09:47
  • @andreamazz Can you please explain this point "To position the view correctly as a subview of the textfield, in front of the text entered, you can use the NSString method sizewithfont:forWidth:lineBreakMode:" I mean how to use this method? Can you please write an example usage? – Anthon Santhez Oct 05 '20 at 09:55
  • @AnthonSanthez this is an 8 years old answer, that method is now deprecated, you can however chack the documentation for its substitute: https://developer.apple.com/documentation/foundation/nsstring/1531844-sizewithattributes – andreamazz Oct 05 '20 at 15:36
  • @andreamazz thank you, I've read the documentation you provided but I couldn't find a sample implementation. Can you show a small example implementation of blinking cursor if not difficult for you? – Anthon Santhez Oct 05 '20 at 16:07