delegate textfield and restrain it only to input numbers - ios

I´m creating some UITextFields programmatically, and when I try to delegate them I receive this warning:
NAVPlanViewController *const __strong' to parameter of incompatible type id<UITextFieldDelegate>
textHeight = [[UITextField alloc] initWithFrame:CGRectMake(0, 120, 160, 40)];
[textHeight setDelegate:self];
and in .c of my class I have added #interface NAVPlanViewController : UIViewController <UITextViewDelegate>.
Also, I need to restrain text field to accept only numbers, I thought to do it with this code but since UITextField wont Delegate I was not able to check it:
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
if (!string.length) {
return YES;
}
if ([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet]
invertedSet]].location != NSNotFound){
//do something;
return NO;
}

In your NAVPlanViewController interface definition, <UITextViewDelegate> should be <UITextFieldDelegate>.

#neilco is right conform to like
#interface YourViewController ()<UITextFieldDelegate>
{
}
#end
And to except only numbers, set the keyboardType to UIKeyboardTypeNumberPad like
UITextField *age = [UITextField autolayoutView];
age.placeholder = kPlaceholderToEnterAge;
age.borderStyle = UITextBorderStyleRoundedRect;
age.clearButtonMode = UITextFieldViewModeWhileEditing;
age.returnKeyType = UIReturnKeyDefault;
age.keyboardType = UIKeyboardTypeNumberPad;
age.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
age.textAlignment = NSTextAlignmentCenter;

Related

textField:shouldChangeCharactersInRange:replacementString: isn't called when inputing in a UITextField

I have a UITextField and I want it has a maximum text length of 20. So I let self(the current view controller) agree to <UITextFieldDelegate> and set self as the text field's delegate, and use the following method to set a maximum length:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.nickNameTextField)
{
if (textField.text.length > 20)
return NO;
}
return YES;
}
However when I insert a breakpoint in this function I found that this function wasn't called when I typed in any words, much less when the text's length exceeds 20. Can somebody tell me why?
You probably haven't linked your textfield with the delegate
Right click on textField which you want to have delegated and drag the textField on the viewcontroller and drop to select the delegate.
I show you steps and screenshot for connecting textField and delegate with XIB or Storyboard.
In storyboard
STEP 1: Click the TextField
STEP 2: Drag the TextField to ViewController
STEP 3: Click "control+mouse" on TextField to ViewController.h and line shows
STEP 4:Now Box will appear and give the TextField Name
STEP 5:Right Click the TextField in ViewController
STEP 6:Hook Up the Delegate to ViewController
If you want to programmatically create the textField
UITextField *txtfldMaxLength = [[UITextField alloc] initWithFrame:CGRectMake(30, 100, 250, 50)];
txtfldMaxLength.borderStyle = UITextBorderStyleRoundedRect;
txtfldMaxLength.textColor = [UIColor blackColor];
txtfldMaxLength.backgroundColor = [UIColor clearColor];
txtfldMaxLength.font = [UIFont systemFontOfSize:17];
txtfldMaxLength.placeholder = #"enter something";
txtfldMaxLength.autocorrectionType = UITextAutocorrectionTypeNo;
txtfldMaxLength.keyboardType = UIKeyboardTypeDefault;
txtfldMaxLength.returnKeyType = UIReturnKeyDone;
txtfldMaxLength.clearButtonMode = UITextFieldViewModeWhileEditing;
txtfldMaxLength.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
txtfldMaxLength.delegate = self;
[self.view addSubview:txtfldMaxLength];
Well I've figured out the problem. I use this grammar to instantiate a UITextField:
self.nickNameTextField.delegate = self;
self.nickNameTextField = ({
UITextField *textField = [UITextField new];
textField.placeholder = [BBTCurrentUserManager sharedCurrentUserManager].currentUser.nickName;
textField.textAlignment = NSTextAlignmentLeft;
textField.backgroundColor = [UIColor lightGrayColor];
textField;
});
Originally I set the textField's delegate outside the braces(like the code above). But when I move self.nickNameTextField.delegate = self;inside the braces then it worked. However I have no idea about why this happened, can someone tell me why?

How do I centre UITextField cursor after user input consistently

I have a UITextField that I want to centre all content (text, cursor) at all times. Is this possible in iOS 7? My current initialisation of the view is shown below.
self.textField = [[UITextField alloc] init];
self.textField.delegate = self;
[self.textField setTextAlignment:NSTextAlignmentCenter];
self.textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
self.textField setTranslatesAutoresizingMaskIntoConstraints:NO];
self.textField.placeholder = NSLocalizedString(#"Enter some text", #"The placeholder text to use for this input field");
My requirement for this is that when I click in the UITextField, the placeholder text should disappear, and show the cursor in the middle of the UITextField.
Currently, this seems to be intermittently positioned either in the middle of the text field or on the left of the text field irrelevant of where I click. Anybody got any suggestions as to how I can solve this or is it a known issue in iOS?
If you're creating you UITextField in you Storyboard you should not initialise and alloc it in code.
You need to use you Textfield delegates to accomplish this..
- (void)viewDidLoad
{
[super viewDidLoad];
self.textField.delegate = self;
[self.textField setTextAlignment:NSTextAlignmentCenter];
self.textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
[self.textField setTranslatesAutoresizingMaskIntoConstraints:NO];
self.textField.placeholder = #"Enter some text";
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
//this removes your placeholder when textField get tapped
self.textField.placeholder = nil;
//this sets your cursor to the middle
self.textField.text = #" ";
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
self.textField.placeholder = #"The placeholder text to use for this input field";
}
This surely does the trick.. Please accept the answer if it helps.
UPDATE
With code below when user press backspace the cursor will not align the text to the left.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *proposedNewString = [[textField text] stringByReplacingCharactersInRange:range withString:string];
NSLog(#"propose: %#", proposedNewString);
if ([proposedNewString isEqualToString:#""])
{
textField.text = [#" " stringByAppendingString:textField.text];
}
return YES;
}

Intercept UITextField touch

I would like to intercept a touch on a UITextField, for instance when I first load it I give it a #selector() to load a different method instead of the delegate stuff?
This is my attempt:
descriptionText = [[UITextField alloc] initWithFrame:CGRectMake(10.0, 25.0, infoView.frame.size.width - 20, 100.0)];
descriptionText.backgroundColor = [UIColor whiteColor];
descriptionText.textColor = [UIColor blackColor];
descriptionText.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
descriptionText.userInteractionEnabled = YES;
[descriptionText addTarget:self action:#selector(loadInfoView:) forControlEvents:UIControlEventTouchUpInside];
descriptionText.font = [UIFont fontWithName:#"Helvetica" size:15];
// show view
[infoView addSubview:descriptionText];
However when I debug the method:
- (void)loadInfoView
{
NSLog(#"load other view here");
}
Your problem is in the forControlEvents:: try UIControlEventEditingDidBegin
[descriptionText addTarget:self action:#selector(loadInfoView:) UIControlEventEditingDidBegin];
Your #selector(loadInfoView:) is also wrong if you have - (void)loadInfoView
or #selector(loadInfoView:) and - (void)loadInfoView: (id) sender
or #selector(loadInfoView) and - (void)loadInfoView
However, why you don't use the UITextFieldDelegate?
.m
#interface ViewController () <UITextFieldDelegate>
#property (strong, nonatomic) UITextField *descriptionText;
#end
Remember to:
self.descriptionText.delegate = self;
Then:
-(void) textFieldDidBeginEditing:(UITextField *)textField
{
if (textField == self.descriptionText)
{
[self loadInfoView];
}
}
Keyboard:
If you don't want to show the keyboard you need to add a [descriptionText resignFirstResponder];
I'm not sure you can get actions to be called on a text field on touch like you want.
If that doesn't work, why don't you attach a tap gesture recognizer to your text field?

textFieldShouldEndEditing not fire when users switch in another UItxextField

i have this code for textFieldShouldEndEditing:
-(void)textFieldDidEndEditing:(UITextField *)textField
{
NSDecimalNumber *testIfNumber = [[NSDecimalNumber alloc] initWithString:[textField text]];
if (![testIfNumber isEqualToNumber:[NSDecimalNumber notANumber]])
{
NSLog(#"%#",[testIfNumber stringValue]);
[[self labelTotal]setText:[self getTotalforRate:[expenseCategorySelected categoryRate] forAmmountField:textField]];
}
}
Now my problem is that in my ViewController I have two or more textField and when a user goes directly from one to another textField this method is not fired.
Is there a method or a way to know when I'm going from a textField to another?
Thx.
You are wrong... textFieldShouldEndEditing is not for this purpose.
Just using textFieldDidEndEditing
Do like this if u dont get
#import "ViewController.h"
#interface ViewController ()<UITextFieldDelegate>//heare set the delegate
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITextField *textField1 = [[UITextField alloc]initWithFrame:CGRectMake(30, 40, 200, 35)];
UITextField *textField2 = [[UITextField alloc]initWithFrame:CGRectMake(30, 80, 200, 35)];
UITextField *textField3 = [[UITextField alloc]initWithFrame:CGRectMake(30, 125, 200, 35)];
textField1.placeholder = #"I am 1st field";
textField2.placeholder = #"I am 2nd field";
textField3.placeholder = #"I am 3rd field";
//set the delegate for all text fields
textField1.delegate = self;
textField2.delegate = self;
textField3.delegate = self;
textField1.tag = 100;
textField2.tag = 200;
textField3.tag = 300;
[self.view addSubview:textField1];
[self.view addSubview:textField2];
[self.view addSubview:textField3];
}
//implement the delegate methods
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if(textField.tag == 100)
{
NSLog(#"i am end editing -> %#",textField.text);
}
else if (textField.tag == 200)
{
NSLog(#"i am end editing -> %#",textField.text);
}
else if (textField.tag == 300)
{
NSLog(#"i am end editing -> %#",textField.text);
}
}
Hope this helps u .. :)

UIPicker in UITextField

I wanna show a picker when I click inside a UITextField. This is my code (which works):
[super viewDidLoad];
// Picker View dei Tipi
pickerTipo= [[UIPickerView alloc] init];
pickerTipo.showsSelectionIndicator = YES;
UIToolbar* keyboardDoneButtonView = [[UIToolbar alloc] init];
[keyboardDoneButtonView sizeToFit];
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc]
initWithTitle:
#"Fine" style:UIBarButtonItemStyleBordered
target:self
action:#selector(pickerDoneClicked:)];
[keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];
self.textTipo.inputAccessoryView = keyboardDoneButtonView;
[self.textTipo resignFirstResponder];
self.textTipo.inputView = pickerTipo;
self.textTipo.delegate = self;
The picker and the accessory view show correctly. The problem is that the UITextField is still editable, that is I can still typing inside the UITextField. I would that when the picker is shown, no editing is enabled inside the UITextField.
[SOLVED}
Following the accepted answer, the right code is :
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.textTipo || textField == self.textStato)
return NO;
else
return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([textField.restorationIdentifier isEqualToString:#"textFieldIdentifier"])
{
return NO;
}
}
Hope it helps.
Instead of textfied you can use button with a background uiimage view of text field.
try this code:
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField;
{
if(textField==self.textTipo)
{
return NO;
}
else
{
return YES;
}
}
make your textfield a readonly property

Resources