views:

284

answers:

1

im using customkeyboard in my controller. but how to get the cursor location in the uitextfiled. my requirement is to enter a charecter in a desired location of textfield. is it possible?

+1  A: 
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    DEBUGLOG(@"range length : %d range location : %d",range.length,range.location);
    return YES;
}

Using this delegate you will get the location where exactly you are adding the character. This will do the job for you. But make sure to set the textfield delegate :)

If u have Textfield like

uitextfield *textField; 

in you .m file somewhere in viewDidLoad just add the line of code:

textField.delegate = self;

and implement the above delegate method.

NOTE: In .h file ex:

#import <UIKit/UIKit.h>


@interface exampleClass : UIViewController <UITextFieldDelegate>
{
    UITextField *mTextField;
}
@property(nonatomic,retain) IBOutlet UITextField textField;

@end

and in .m file:

 @implementation exampleClass
 @synthesize textField = mTextField;


 - (void)viewDidLoad 
{
    [super viewDidLoad];
    [self.textField setDelegate:self];
}

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
 {
     DEBUGLOG(@"range length : %d range location : %d",range.length,range.location);
     return YES;
 }
@end
Manjunath
im using customkeyboard and custom keys. how to fire this method? how to get nsrange from textfield? thanks for ur reply
Allen
This is the delegate method for a textfield. You just set the textfield delegate. Just check the updated post.
Manjunath
yah you are right but im using customkeyboard. when i click on the button in the custom keyborad how this delegate method fire?
Allen
I was bit late on updating my answer:). Check it out you will get to know how to set the delegate.
Manjunath
Whatever keyboard you use, but ultimately you will be typing into the textfield right? So by setting textfield's delegate you will get the callback.
Manjunath
you mean when i press the button and set text to textfield the delegate will fire.
Allen
yes for each character you type, this delegate will fire.
Manjunath
i dont know if im missing something. i set the textfield delegate, but there is no callback. (eg: i clicked '1' button on my customkeyboard it will fire a method,there im appending'1' to the text. it will never callback any textfield methods.
Allen
Are you using setText: to set the text?
Manjunath
im using textfield.text for seting text.
Allen
oh ok. Then get the string length from the text field. It will give you the length of text in textfield. And that will be the location where you are going to enter your next character.
Manjunath
i have to enter in middile of the string. so the length of the string is not possible. i have to know the cursor position. thanks for ur reply.
Allen