I have aUISearchBar, I get theUITextfield in it and then I want to set selected Text range but it's always return nil. This is my code:
UITextField *searchField = [self.searchBar valueForKey:#"_searchField"];
[searchField becomeFirstResponder]; // focus to this searchfield
And I fill in the text:
self.searchBar.text = #"This is text";
And checked if theUITextField text is filled in and it is. Still, all the methods regardingUITextPosition andUITextRange return nil:
UITextRange *selectedRange = [searchField selectedTextRange]; //selectedRange = nil
UITextPosition *newPosition = [searchField positionFromPosition:selectedRange.start offset:addressToComplete.street.length]; //newPosition = nil
UITextRange *newRange = [searchField textRangeFromPosition:newPosition toPosition:newPosition]; //newRange = nil
My code is wrong something?
Have you tried Logging UITextField *searchField? its nil from the looks of it.. i think your code is supposed to be..
(UITextField *)[self.searchBar valueForKey:#"_searchField"]
([after trying your code] OooOoKayyy.. it works.. hahaha..) By the way this is how i get UITextField inside searchBar..
for (id object in [[[self.searchBar subviews] objectAtIndex:0] subviews])
{
if ([object isKindOfClass:[UITextField class]])
{
UITextField *searchField = (UITextField *)object;
break;
}
}
First i tried what you have which is:
UITextField *searchField = (UITextField *)[searchBar valueForKey:#"_searchField"];
searchBar.text = #"This is text";
// and logging your searchField.text here.. returns nil/empty..
and i tried rearranging it like this...
searchBar.text = #"This is text";
UITextField *searchField = (UITextField *)[searchBar valueForKey:#"_searchField"];
NSLog(#"searchFields.text :%#", searchField.text);
again i tried your code under -(void)viewDidLoad but no good, yeah it is always nil as you said.. now it looks like this..
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
searchBar.text = #"This is text"; // not important
UITextField *searchField = [searchBar valueForKey:#"_searchField"];
[searchField becomeFirstResponder];
UITextRange *selectedRange = [searchField selectedTextRange]; //selectedRange = not nil anymore
NSLog(#"searchField.text :%# -> selectedRange :%#\n\n" , searchField.text, selectedRange);
}
//i've also tried it inside uibutton's event and i worked .. >.<
i programmatically selectedTextRange(for example purposes) and probably it something to do with the xibs autolayout or something (weird i dont experience it) but there it is, try it.. :)
i hope i've helped you..
Happy coding.. Cheers!
Related
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;
}
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
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)
I'm trying to remove the textborderstyle of the UITextField in a UISearchBar. I know that I'm getting reference to the correct object, as I'm able to change the TextBorderStyle to RoundedRect and see a visible change.
I've tried subclassing UISearchBar with the following code:
- (void)layoutSubviews {
UITextField *searchField;
NSUInteger numViews = [self.subviews count];
for(int i = 0; i < numViews; i++) {
if([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) { //conform?
searchField = [self.subviews objectAtIndex:i];
}
}
if(!(searchField == nil)) {
[searchField setBorderStyle:UITextBorderStyleNone];
}
[super layoutSubviews];
}
I've also tried this inside a class:
UITextField *txtSearchField = [_searchBar valueForKey:#"_searchField"];
[txtSearchField setBackgroundColor:[UIColor clearColor]];
[txtSearchField setBorderStyle:UITextBorderStyleNone];
Neither of these work. By default, it seems to have UITextBorderStyleLine if I manually set it to None. I unfortunately haven't been able to find a way to remove the border style. Does anyone know how to do this? I'm trying to figure this out since I need my search bar to look like a UITextField. I'm debating just switching to a UITextField behind the scenes at this point.
I'm pretty certain that the only way to achieve this is to subclass UISearchBar!
Try this code in your layoutSubviews method once you have subclassed it!
- (void)layoutSubviews {
UITextField *searchField;
NSUInteger numViews = [self.subviews count];
for(int i = 0; i < numViews; i++) {
if([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) { //conform?
searchField = [self.subviews objectAtIndex:i];
}
}
if(!(searchField == nil)) {
searchField.textColor = [UIColor whiteColor];
[searchField setBackground: [UIImage imageNamed:#"buscador.png"] ];
[searchField setBorderStyle:UITextBorderStyleNone];
}
[super layoutSubviews];
}
The question found here remove the border of uitextfield in uisearchbar answers your initial question!
You can also reference How to customize apperance of UISearchBar for more information!
Hope this helps!
Just not to overlook the comment (I just did, when I landed in this same issue and came to this question). If,programmatically, your UITextField's borderStyle does 'not' get set to UITextBorderStyleNone, then try setting the background or backgroundColor property of the UITextField 'before' setting its borderStyle! And it works!
I have some dynamically allocated texfields and in which i am entering the text,
Now i have got two problems here
1) After 2-3 button clicks, i mean changing the views and coming back to the same view than the data is not being removed from the textfield the previous data in the textfield is being present.
the code i have tried with are
answerTextField.text = #"";
answerTextField.text = nil;
2) I am unable to delete the textfield data in which i am appending the data that is coming from the textfield.text
-(void) keyPressed: (NSNotification*) notification {
if ([[[notification object]text] isEqualToString:#" "])
{
UITextField *textField = (UITextField *)[self.view viewWithTag:nextTag];
textField.text = #"";
[textField becomeFirstResponder];
nextTag = textField.tag;
}
else
{
[[NSNotificationCenter defaultCenter] removeObserver: self name:UITextFieldTextDidChangeNotification object: nil];
NSLog(#"TextField tag value :%d",tagCount);
NSLog(#"TextField next tagg tag value :%d",nextTag);
if (tagCount == nextTag+1)
{
UITextField *textField = (UITextField *)[self.view viewWithTag:nextTag];
[textField resignFirstResponder];
NSLog(#"append string :%#",appendString);
}
else
{
NSLog(#"TextField nexttag value before :%d",nextTag);
nextTag = nextTag + 1;
NSLog(#"Letter is%#",[[notification object]text]);
str= [[NSString alloc]initWithFormat:#"%#",[[notification object]text]];
NSLog(#"TextField String :%#",str);
NSLog(#"TextField nexttag value after :%d",nextTag);
[appendString appendString:[NSString stringWithFormat:#"%#",str]];
NSLog(#"Content in MutableString: %#",appendString);
}
NSLog(#"The tags in keypressed:%d",nextTag);
UITextField *textField = (UITextField *)[self.view viewWithTag:nextTag];
[textField becomeFirstResponder];
}
// For inserting Spaces taken from array.
if(tagCount+300 == nextTag)
{
for (int m=0 ; m< [intArray count]; m++)
{
[appendString insertString:#" " atIndex:[[intArray objectAtIndex:m]intValue]];
NSLog(#"FinalString : %#",appendString);
}
}
}
Edited: The textfield data that i am storing is being made nil, but the on the textfield the data is being remained it is not being removed, for the textfield i have added a background image, do not know whether it makes any difference or not, i am attaching the code for it:
UIImageView *myView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"text_line.png"]];
myView.center = CGPointMake(5, 27);
[letterField insertSubview:myView atIndex:0];// mgViewTitleBackGround is image
[myView release];
To clear text field do this code in viewWillAppear:
NSArray *arraysubViews = [self.view subViews];
for(UIView *subView in arraysubViews){
if([subView isKindOfClass:[UITextField class]]){
// if(subView.tag == MY_TEXT_VIEW_TAG)
(UITextField *)subView.text = #"";
}
}
This will remove the text in every UITextField in your view. If you need to clear some textfields only, uncomment the code; which will check against tag value
EDIT
NSArray *arraysubViews = [self.view subviews];
for(UIView *subView in arraysubViews){
if([subView isKindOfClass:[UITextField class]]){
// if(subView.tag == MY_TEXT_VIEW_TAG)
UITextField *textField = (UITextField *)subView;
textField.text = #"";
}
}
UIView does not have a subViews method. It is subViews instead.