change font color of empty uitextfield - ios

I have a UITextfield and when the text field is equal to "test", I want to clear out the text field and change the font color to green. The code below almost accomplishes it.
- (void)editingDidBegin:(id)sender {
UITextField *txtfld = (UITextField*)sender;
if ([txtfld.text isEqualToString:(#"test")]) {
txtfld.text = #" ";
[txtfld setFont:regularFont];
[txtfld setTextColor:[UIColor greenColor]];
}
}
The only problem is I want to change:
txtfld.text = #" ";
to:
txtfld.text = #"";
When I do that, the font color remains the original black color. If I leave it as #" " then the font changes to green. Any ideas? Thanks in advance.
Scenario:
(1) user enters nothing in the text field and clicks the submit button - works
(2) the submit button updates the text field with the word "test" and makes it red - works (3) when the user goes back to the text field I want the word test deleted and when the user types for all the text to green. - Doesn't work
Note: I placed my code in the event "Editing Did Begin" as i figured when the user goes to update the field it should clear the text and allow them to type in green font color.

It is interesting that when you set text to #"" or nil, and also set textColor in UIControlEventEditingDidBegin event handler, the textColor is not set what so ever. So the silver lining is to set textColor at a later time, also see the comments in code:
- (IBAction)textEditingDidBegin:(id)sender
{
UITextField *field = (UITextField *)sender;
if ([field.text isEqualToString:#"test"]) {
[field setText:#""];
[self performSelector:#selector(setColor:) withObject:sender afterDelay:0.01];
[field setFont:[UIFont fontWithName:#"Georgia" size:15]];
}
}
- (void)setColor:(id)sender
{
// See this line of code closely, do NOT use sender, use textField property in your view controller class
[self.textField setTextColor:[UIColor greenColor]];
}

I just tested your code. It should work. You are reverting the color elsewhere.
You can test it in a new single view project with this code:
#import "ViewController.h"
#interface ViewController () <UITextFieldDelegate>
#property (nonatomic, weak) IBOutlet UITextField *textField;
-(IBAction)checkColor:(UIButton *)sender;
#end
#implementation ViewController
-(void)checkColor:(UIButton *)sender {
_textField.text = #"check color";
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
if ([textField.text isEqualToString:#"test"]) {
textField.text = #"";
textField.textColor = [UIColor greenColor];
}
else {
textField.textColor = [UIColor darkTextColor];
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
#end

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?

How to change the position or hide magnifier icon in UISearchBar in IOS 7?

I am working on IOS 7 application.By default its appearing like Pic(1).But I need to change it as Pic(2).I googled and found few answers for the requirement,but it has not changed.Or else I need to hide.So that I can manage with background image.This is first image
I used below code to modify it.But didnt succeed.
In .h file
#property(nonatomic,strong) IBOutlet UISearchBar *findSearchBar;
In .m file
#synthesize findSearchBar;
- (void)viewDidLoad
{
[super viewDidLoad];
[self setSearchIconToFavicon];
}
- (void)setSearchIconToFavicon
{
// The text within a UISearchView is a UITextField that is a subview of that UISearchView.
UITextField *searchField;
for (UIView *subview in self.findSearchBar.subviews)
{
if ([subview isKindOfClass:[UITextField class]]) {
searchField = (UITextField *)subview;
break;
}
}
if (searchField)
{
UIView *searchIcon = searchField.leftView;
if ([searchIcon isKindOfClass:[UIImageView class]])
{
NSLog(#"aye");
}
searchField.rightView = nil;
searchField.leftView = nil;
searchField.leftViewMode = UITextFieldViewModeNever;
searchField.rightViewMode = UITextFieldViewModeAlways;
}
}
I am not getting how to make the center of the view's image to nil.Its really killing my time.Please help me.where I had gone wrong.
UITextField *txfSearchField = [looksearchbar valueForKey:#"_searchField"];
[txfSearchField setBackgroundColor:[UIColor whiteColor]];
[txfSearchField setLeftViewMode:UITextFieldViewModeNever];
[txfSearchField setRightViewMode:UITextFieldViewModeNever];
[txfSearchField setBackground:[UIImage imageNamed:#"searchbar_bgImg.png"]];
[txfSearchField setBorderStyle:UITextBorderStyleNone];
//txfSearchField.layer.borderWidth = 8.0f;
//txfSearchField.layer.cornerRadius = 10.0f;
txfSearchField.layer.borderColor = [UIColor clearColor].CGColor;
txfSearchField.clearButtonMode=UITextFieldViewModeNever;
Try this may be it will help u........
I'm not sure how to left-align the placeholder, but as of iOS 5.0 there's a simple, supported way to modify the search bar's text field properties, e.g.:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setLeftViewMode:UITextFieldViewModeNever];
which will hide the magnifying glass icon.
You could try:
searchBar.setImage(UIImage(named: "yourimage")!, forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Normal)

UIKeyboardTypeNamePhonePad - Display options

I need to use the, Name Phone Keyboard type (UIKeyboardTypeNamePhonePad) but having the number pad appear first when the text field is selected.
I need to input data such as
123 -
657 -
450b -
123a
I always need input a number first, but occasionally either a A / B at the end.
You can try to change keyboard type in function of the size of the string:
Implement delegate UITextFieldDelegate
Then set defaut textfield keyboard;
[textField setKeyboardType:UIKeyboardTypeNumberPad];
[textField setDelegate:self];
Then in the following method, change the keyboard when text size equals 3:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([[textField text] length] > 3)
{
[textField setKeyboardType:UIKeyboardTypeDefault];
[textField reloadInputViews];
}
return YES;
}
Another solution is to add an accessory view button (you can change of keyboard manually):
- (void)viewDidLoad
{
[super viewDidLoad];
textField.keyboardType = UIKeyboardTypeNumberPad;
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(0, 0, 50, 50)];
[button addTarget:self action:#selector(changeKeyboard) forControlEvents:UIControlEventTouchDown];
textField.inputAccessoryView = button;
}
-(void)changeKeyboard
{
if([textField keyboardType] == UIKeyboardTypeNumberPad)
{
textField.keyboardType = UIKeyboardAppearanceDefault;
}
else
{
textField.keyboardType = UIKeyboardTypeNumberPad;
}
[textField reloadInputViews];
}
click on the textfield,then go to Hide or show utilities ie View(you will find it at right hand side beside the editor.There you select the third view ie the most right one).
Then you click the attributes inspector.In that you will find a menu called "keyboard" which is set as default,but you can select whichever pad you want.
Hope it works for you.

Resources