Can we call a method by tapping on UITextField in iPhone sdk - iphone

countryField=[[UITextField alloc]initWithFrame:CGRectMake(0,0,100,25)];
countryField.textColor = [UIColor blackColor];
countryField.font = [UIFont systemFontOfSize:15.0];
countryField.backgroundColor = [UIColor redColor];
countryField.keyboardType = UIKeyboardTypeDefault;
countryField.enabled=NO;
countryField.delegate = self;
[countryField addTarget:self action:#selector(getCountry:) forControlEvents:UIControlEventEditingChanged];
[myView addSubview:countryField];
-(void)getCountry:(id)sender
{
printf("\n hai i am in getCountry method");
}

Your Code looks like you want your TextField disabled. The method is only called if you enable your UITextField.
But when you enable your UITextField the Keyboard appears and the User is able to edit the text. To prevent that you have to implement the - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField method (from the UITextFieldDelegate Protocol) and just return NO.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
return NO;
}
In short: Enable your UITextField, implement the method above and change your Control Event to UIControlEventTouchUpInside (I think this is what you want !).

Change your code to
countryField=[[UITextField alloc]initWithFrame:CGRectMake(0,0,100,25)];
countryField.textColor = [UIColor blackColor];
countryField.font = [UIFont systemFontOfSize:15.0];
countryField.backgroundColor = [UIColor redColor];
countryField.keyboardType = UIKeyboardTypeDefault;
// IF YOU WANT CERTAIN METHOD TO GET FIRE WHEN TAPPED ON TEXTFIELD YOU HAVE TO ENABLE THE TEXTFIELD
// countryField.enabled=NO;
countryField.delegate = self;
// [countryField addTarget:self action:#selector(getCountry:) forControlEvents:UIControlEventEditingChanged];
[myView addSubview:countryField];
Then in the delgate method of textfield call the function you want to call i.e.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[self getCountry];
return YES;
}
Where the function is
-(void)getCountry
{
printf("\n hai i am in getCountry method");
}
hAPPY cODING...

You could add a target for the UIControlEventTouchDown event just like you did for the UIControlEventEditingChanged event.

Related

Dissmissing the keyboard when UITextField and UITextview displayed inside of UIWindow

I've added my UITextField and UITextView inside a UIWindow I can not able to type inside in both of them. Both are not letting me allow to type in those fields. And, can't able to dismiss it when return pressed in keyboard.
-(void)showAlert
{
alertWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
alertView = [[UIView alloc] initWithFrame:CGRectMake(10, 115, 300, 230)];
alertWindow.windowLevel = UIWindowLevelAlert; // puts it above the status bar
alertView.center = CGPointMake(alertWindow.frame.size.width/2, alertWindow.frame.size.height/2);
alertView.backgroundColor = [UIColor whiteColor];
alertView.layer.borderWidth = 1.0;
alertView.layer.borderColor = [[UIColor whiteColor]CGColor];
UITextField *txt = ....
....
....
txt.delegate = self;
...
...
[alertView addSubview:txt];
UITextView *txtview = ...
....
....
txtview.delegate = self;
...
[alertView addSubview:txtview];
[alertWindow addSubview:alertView];
[alertWindow addSubviewWithZoomInAnimation:alertView duration:1.0 option:curveValues[0]];
[alertWindow setHidden:NO];
}
I've declared both of the delegate methods also. I placed a breakpoint there and checked also, even that method not yet called.
Update -
textFieldShouldReturn delegate method
- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
[reserveView resignFirstResponder];
[reserveWindow resignFirstResponder];
[self.reserveWindow endEditing:YES];
[reserveView endEditing:YES];
return YES;
}
You should try this for dismiss the keyboard from the UIWindow
[self.window endEditing:YES];
Source
I found, that method has not been called because of UIWindow So, i changed my UIWindow to UIView And, i fixed this issue by using UIView+Animation.h from here It provides the animation what i required exactly.
- (void) addSubviewWithZoomInAnimation:(UIView*)view duration:(float)secs option:(UIViewAnimationOptions)option;
- (void) removeWithZoomOutAnimation:(float)secs option:(UIViewAnimationOptions)option;
Thanks to Google! Cheers!
The keyboard will never dismiss on its own (even if you hit return!). You'll notice that in your delegate methods, you will receive events whenever you press return/done/etc.
A simple way to make the keyboard dismiss every time someone hits the return key is to implement the - (BOOL)textViewShouldEndEditing:(UITextView *)textView method.
- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
[textView endEditing:YES];
return YES;
}
Edit: In your post you edited to say that you've declared both of the delegate methods... there are more than two so could you clarify what methods you've implemented? http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextViewDelegate_Protocol/Reference/UITextViewDelegate.html#//apple_ref/occ/intf/UITextViewDelegate
Try this
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(dismissKeyboard)];
tapGesture.cancelsTouchesInView = NO;
[self.window addGestureRecognizer:tapGesture];
//[self.view addGestureRecognizer:tapGesture];
[tapGesture release];
}
-(void)dismissKeyboard
{
[txt resignFirstResponder];
[textView resignFirstResponder];
}
Try this
That's the delegate method of textfield:-
(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[txtview resignFirstResponder];
return NO;
}

Detecting backspace in UITextField the right way

Attention! This question is not a duplicate of this or this question! This is a new question to make things more clear.
So I have followed all the instructions of the posts above and I have this UITextField that becomes empty and moves to a new position every time the user hits return button. Moreover, I trace the input of the textView and I create a label of that text in the position the TextView was, like this:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField.text.length > 5) {
CGRect labelFrame = CGRectMake(textField.frame.origin.x, textField.frame.origin.y, 0, 0);
UILabel *label = [[UILabel alloc] initWithFrame: labelFrame];
label.font = [UIFont fontWithName:#"HelveticaNeue" size:14];
[label setText:textField.text];
[label setTextColor: [BSFunctions getColorFromHex:#"3f3f3f"]];
label.backgroundColor =[UIColor lightGrayColor];
[label sizeToFit];
[labelsArray addObject:label];
[self.view addSubview: label];
CGRect newTextFieldFrame = CGRectMake(labelFrame.origin.x + label.frame.size.width + 5, labelFrame.origin.y, 320, 30);
NSLog(#"Rect is %#", NSStringFromCGRect(newTextFieldFrame));
textField.frame = newTextFieldFrame;
textField.text = #"\u200B";
}
return YES;
}
I set the text in UITextField text to be #"\u200B" and I then want to detect the backspace button on it like this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([string isEqualToString:#""]) {
NSLog(#"backspace button pressed");
if (labelsArray.count > 0) {
UILabel *labelToDelete = [labelsArray lastObject];
CGRect labelPosition = labelToDelete.frame;
CGRect oldPosition = textField.frame;
textField.frame = CGRectMake(labelPosition.origin.x, labelPosition.origin.y, oldPosition.size.width, oldPosition.size.height);
[labelToDelete removeFromSuperview];
[labelsArray removeLastObject];
textField.text = #"\u200B";
}
}
return YES;
}
But the problem is, it works only once and then, even with the special character added at the beginning of the textField it doesn't work. What is possibly wrong?
After setting
textField.text = #"\u200B";
in textField:shouldChangeCharactersInRange:replacementString:
You will have to add
return NO;
otherwise it will continue to the return YES and replace it with a #"" and then when pressing the backspace once again nothing will be changed and the delegate method will not be called.
It is possible that I misunderstood your goal here, but I hope this helps.

Firing didEndOnExit programmatically

I have many textfields created in my application, and i want them to close keyboard when user finishes editing. I know that if textField's created by IB, and there is an IBAction i can use but what if the textField's created like this,
int top = 60;
for(NSUInteger i=0; i< [kArray count]; i++){
UITextField *kField = [kArray objectAtIndex:i];
kField.frame = CGRectMake(130, top, 60, 30);
kField.borderStyle = UITextBorderStyleRoundedRect;
kField.autocorrectionType = UITextAutocorrectionTypeNo;
kField.returnKeyType = UIReturnKeyDone;
kField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
[scrollView addSubview:kField];
top += 50;
}
How can i close the keyboard when user presses done button?
Use UITextFieldDelegate method:
#pragma mark UITextFieldDelegate methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
Remember to make your class comply with delegate like so:
#interface MyViewController : UIViewController <UITextFieldDelegate>
Try this:
- (BOOL)textFieldShouldReturn: (UITextField *)textField {
[kField resignFirstResponder];
return YES;
}

My UITextView is not calling any delegate methods

My problem is that none of the delegate methods of UITextView get called.
My code, I've not included the whole class, just the relevant parts.
I'm not using an XIB, its all added programatically.
None of my delegate methods get called.
.h
#interface ChatAppViewController : UIViewController <UITableViewDelegate,
UITableViewDataSource, UITextViewDelegate>
{
UITextView * messageTextField;
}
.m
- (void)viewDidLoad
{
messageTextField = [[UITextField alloc] initWithFrame:CGRectMake(5, 408, 310, 70)];
messageTextField.textColor = [UIColor blackColor]; //text color
messageTextField.font = [UIFont systemFontOfSize:17.0]; //font size
[messageTextField setPlaceholder:#"Post a message" ];
messageTextField.backgroundColor = [UIColor whiteColor]; //background color
messageTextField.autocorrectionType = UITextAutocorrectionTypeNo;
messageTextField.keyboardType = UIKeyboardTypeDefault; // type of the keyboard
messageTextField.returnKeyType = UIReturnKeyDone; // type of the return key
messageTextField.delegate = self;
messageTextField.hidden = NO;
[self.view addSubview:messageTextField];
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
NSLog(#"textViewShouldBeginEditing");
return YES;
}
- (void)textViewDidBeginEditing:(UITextView *)textView {
NSLog(#"textViewDidBeginEditing");
}
- (void)textViewDidChange:(UITextView *)textView {
NSLog(#"textViewDidChange");
}
- (void)textViewDidChangeSelection:(UITextView *)textView {
NSLog(#"textViewDidChangeSelection");
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
NSLog(#"textViewShouldEndEditing");
return YES;
}
- (void)textViewDidEndEditing:(UITextView *)textView {
NSLog(#"textViewDidEndEditing");
}
Many Thanks,
-Code
This line:
messageTextField = [[UITextField alloc] initWithFrame:...
Creates a UITextField, not a UITextView.
Simple. You created a UITextField object. That is why none of the delegate methods were not called - because they were the wrong ones. Replace your viewDidLoad with the following:
- (void)viewDidLoad
{
messageTextField = [[UITextView alloc] initWithFrame:CGRectMake(5, 408, 310, 70)];
messageTextField.textColor = [UIColor blackColor]; //text color
messageTextField.font = [UIFont systemFontOfSize:17.0]; //font size
messageTextField.backgroundColor = [UIColor whiteColor]; //background color
messageTextField.autocorrectionType = UITextAutocorrectionTypeNo;
messageTextField.keyboardType = UIKeyboardTypeDefault; // type of the keyboard
messageTextField.returnKeyType = UIReturnKeyDone; // type of the return key
messageTextField.delegate = self;
messageTextField.hidden = NO;
[self.view addSubview:messageTextField];
}
Compile it and now delegate functions should fire just fine.
If you create UITextField in .xib, then declare in .h as IBOutlet... And connect textfield's delegate to File's Owner, otherwise everything should be perfect.

Can I programmatically fire the "switch to number pad" button on iPhone keyboard

I want to find a way to programmatically fire the selector that causes the iPhone keyboard to switch from letters to numbers. I am aware that I can switch the keyboard type, but I want to know if there is a way to do this without switching the keyboard type.
You cannot switch keyplanes (alphabetic keyplane to numeric keyplane to symbol keyplane) programatically, at least not in any way that is publicly supported. As you mentioned, you can change the keyboard type or appearance of the text input traits of the first responder, but this is different than switching between the different keyplanes, which only the user should be able to do.
Just a workaround:
When you want to change the keyplane of an active keyboard like from alphabet to number pad while editing an UITextField, first set the new value to the keyboardType property of the textfield, next send a resignFirstResponder, finally a becomeFirstResponder message to the textfield. E.g.
textfield.keyboardType = UIKeyboardTypeNumberPad;
[textField resignFirstResponder];
[textField becomeFirstResponder];
Swift:
textField.keyboardType = .numberPad
textField.resignFirstResponder()
textField.becomeFirstResponder()
Hope it helps ;-D
For custom switching keyboard types you can use accessoryView of Keyboard
Code to make the keyboard accessoryView for type switching... (hopefully the snipped code is understandable)
// You can call this in viewDidLoad (initialization of the ABC/Done view)
- (void)setAccessoryViewForKeyboard{
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 44)];
UIBarButtonItem *changeKeyboard = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStylePlain target:self action:#selector(switchKeyboardTypes)];
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *choose = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(#"Done", #"") style:UIBarButtonItemStylePlain target:_textField action:#selector(resignFirstResponder)];
[toolbar setItems:#[changeKeyboard, space, choose]];
[self.textField setInputAccessoryView:toolbar];
}
// changing the left button text ('ABC' and '123')
- (void)setTitleForSwitchingKeyboardButton{
NSString *firstButtonText = self.textField.keyboardType == UIKeyboardTypeDefault ? NSLocalizedString(#"123", #"") : NSLocalizedString(#"ABC", #"");
[[[(UIToolbar *)self.textField.inputAccessoryView items] firstObject] setTitle:firstButtonText];
}
- (void)switchKeyboardTypes{
if (self.textField.keyboardType == UIKeyboardTypeDefault){
[self setTextFieldKeyboardType:UIKeyboardTypeNumberPad];
} else {
[self setTextFieldKeyboardType:UIKeyboardTypeDefault];
}
}
- (void)setTextFieldKeyboardType:UIKeyboardTypeNumberPad:(UIKeyboardType)keyboardType {
[self.textField setKeyboardType:keyboardType];
if ([_textField isFirstResponder]) {
_changingKeyboardType = YES;
[self.textField resignFirstResponder];
[self.textField becomeFirstResponder];
_changingKeyboardType = NO;
}
[self setTitleForSwitchingKeyboardButton];
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if (!_changingKeyboardType) {
// you can set the default keyboard type here:
// [self setTextFieldKeyboardType:UIKeyboardTypeNumberPad];
// [self setTextFieldKeyboardType:UIKeyboardTypeDefault];
[self setTitleForSwitchingKeyboardButton];
}
}
Have a look at this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * cellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil)
{
cell = [ [ [UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14.0f];
cell.textLabel.textColor = [UIColor whiteColor];
}
UITextField * textField = [ [ UITextField alloc] initWithFrame:CGRectMake(55.0f, 10.0f, 230.0f, 31.0f)];
textField.textColor = [UIColor whiteColor];
textField.delegate = self;
c this care fully ///////////if(indexPath.row == 0)
c this care fully // textField.keyboardType = UIKeyboardTypeDefault;
c this care fully //else
c this care fully // textField.keyboardType = UIKeyboardTypePhonePad;
textField.autocorrectionType = UITextAutocorrectionTypeNo;
[cell.contentView addSubview:textField];
if(indexPath.row == 0)
{
self.sender = textField;
cell.textLabel.text = #"From:";
}
else
{
self.mobileNumber = textField;
cell.textLabel.text = #"To:";
}
[textField release];
if(indexPath.row == 1)
{
UIButton * contactsButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
[contactsButton addTarget:self action:#selector(addContact:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = contactsButton;
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
Check where I commented "c this care fully"
This will help you to switch keyboards programmatically.
Maybe
keyboardType = .numbersAndPunctuation
will help. It starts the keyboard in numeric mode and you can switch back to alphabet.