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.
Related
I have four UITextFields that I would like to use in a UIAlertView, Currently this is what it is looking like
What I would like to be able to do is restrict each box to 4 characters once each field once that 4 character limit is reached then I would like the next UITextField to become the first responder.
I would also like to be able to do this in reverse so if characters are being deleted once there are no characters available in the second field go to the first and start deleting etc.
Currently my code is pretty sloppy as I am just trying to get something like this working.. so this is what it looks like so far.
//prompt user to enter registration here
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Please Register Device" message:#" " delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12, 45, 53, 30)];
UITextField *myTextField1 = [[UITextField alloc] initWithFrame:CGRectMake(77, 45, 53, 30)];
UITextField *myTextField2 = [[UITextField alloc] initWithFrame:CGRectMake(142, 45, 53, 30)];
UITextField *myTextField3 = [[UITextField alloc] initWithFrame:CGRectMake(207, 45, 53, 30)];
// need to do something with first reasponder once 4 digits has been entered per box etc.
[myTextField becomeFirstResponder];
myTextField.placeholder =#"AAAA";
myTextField.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
myTextField.textAlignment = NSTextAlignmentCenter;
myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
myTextField1.placeholder =#"AAAA";
myTextField1.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
myTextField1.textAlignment = NSTextAlignmentCenter;
myTextField1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
myTextField2.placeholder =#"AAAA";
myTextField2.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
myTextField2.textAlignment = NSTextAlignmentCenter;
myTextField2.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
myTextField3.placeholder =#"AAAA";
myTextField3.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
myTextField3.textAlignment = NSTextAlignmentCenter;
myTextField3.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[myTextField setBackgroundColor:[UIColor whiteColor]];
[myTextField1 setBackgroundColor:[UIColor whiteColor]];
[myTextField2 setBackgroundColor:[UIColor whiteColor]];
[myTextField3 setBackgroundColor:[UIColor whiteColor]];
[alert addSubview:myTextField];
[alert addSubview:myTextField1];
[alert addSubview:myTextField2];
[alert addSubview:myTextField3];
[alert show];
Any help would be greatly appreciated.
// UPDATE:
this is how I am trying to use the delegate method
//.h
<UITextFieldDelegate>
//.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//..
[self.myTextField setDelegate:self];
[self.myTextField1 setDelegate:self];
[self.myTextField2 setDelegate:self];
[self.myTextField3 setDelegate:self];
//..
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSLog(#"yay");
return NO;
}
Update
I tried the code below, and does work, but for a reason if you change the FirstResponder, the text won't get written. So I modified the function. You should do this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField.text.length >= MAX_LENGTH)
return NO;
if((textField.text.length + string.length) >= MAX_LENGTH)
{
int currentTag = textField.tag;
if(currentTag == 4)
return YES;
UITextField *newTextField = (UITextField *) [textField.superview viewWithTag:(currentTag+1)];
[newTextField becomeFirstResponder];
textField.text = [textField.text stringByAppendingString:string];
}
return YES; //you probably want to review this...
}
Any way, this doesn't work when you wan't to delete content, but that's easy solved if you change the code to check the range of the changes.
I made a sample project, you can get it here: TextFieldTest
This is how I would do it, using the textfield delegate, you can check the new inserted characters, if you reach the maximum, you move to the next textfield:
static int MAX_LENGTH = 4;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if((textField.text.length + string.length) >= MAX_LENGTH)
{
//Get next TextField... A simple way to do this:
UITextField *newTextField = [textField.superview viewWithTag:(textField.tag+1)];
[newTextField becomeFirstResponder];
//remember to set the tags in order
}
return YES; //you probably want to review this...
}
(Sorry if dosen't compile I just wrote it here directly)
Good Luck!
You can set delegate for these text fields and implement your business logic (set one of the text fields as the new first responder) in the delegate methods.
I would like to create a custom UITextView with the ability to enter text in it, as well as programmatically adding some UILabels there that would act like text (I need to delete them with the 'backspace' button when the cursor comes near them).
This UITextView should be expandable and the labels can have different width.
Any ideas of how you can create this sort of thing, any tutorials or such?
you can create textfield using this code.
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 300, 40)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = #"enter text";
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.delegate = self;
[self.view addSubview:textField];
[textField release];
And for creating label you can use this code:
CGRect labelFrame = CGRectMake( 10, 40, 100, 30 );
UILabel* label = [[UILabel alloc] initWithFrame: labelFrame];
[label setText: #"My Label"];
[label setTextColor: [UIColor orangeColor]];
label.backgroundColor =[UIColor clearColor];
[view addSubview: label];
and for deleting label when backspace tape use this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([string isEqualToString:#""]) {
NSLog(#"backspace button pressed");
[label removeFromSuperview];
}
return YES;
}
If the backspace button is pressed, then the replacementString(string) will have null value. So we can identify backspace button press using this.
I try to create the uitextfield dynamically, but i can't create the textfield name.Anybody knows please help me.
from How do I create a text field?
To create a text field, use the UITextField class, as shown in Listing 11.
Listing 11: Creating a text field
CGRect textFieldFrame = CGRectMake(0.0, 0.0, 100.0, 30.0);
UITextField *textField = [[UITextField alloc] initWithFrame:textFieldFrame];
[textField setBorderStyle:UITextFieldBorderStyleBezel];
[textField setTag:1234];
[textField setTextColor:[UIColor blackColor]];
[textField setFont:[UIFont systemFontOfSize:20]];
[textField setDelegate:self];
[textField setPlaceholder:#"<enter text>"];
[textField setBackgroundColor:[UIColor whiteColor]];
textField.keyboardType = UIKeyboardTypeDefault;
Assign tag for each UITextField..
then access the textField using
UITextField *tf=(UITextField *)[yourView viewWithTag:tag];
for (int i=0; i<[checklistArray count]; i++) {
[self addUITextFieldMethod:i]
}
-(void) addUITextFieldMethod:(int)y {
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(20, 70*y+40, 280, 31)];
textField.placeholder = #"Click here to type";
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:15];
textField.textAlignment = NSTextAlignmentLeft;
textField.returnKeyType = UIReturnKeyDefault;
int DropDownTag = [[NSString stringWithFormat:#"10%d",y]integerValue];
textField.tag = DropDownTag ;
textField.delegate = self;
[textField addTarget:self action:#selector(returnFromKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
[scrollViewChecklist addSubview:textField];
}
int textFieldTagValue = textField.tag;
/****************Code In Your Method****************/
UITextField *myTextField = (UITextField *)[self.view viewWithTag:textFieldTagValue];
myTextField.text = [arrayTest objectAtIndex:indexPath.row];
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.
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.