Is it possible to change the alignment of a UISearchBar position?

I will need to show the UISearchBar in different alignments due to different input languages.
I saw this answer , but I can’t find exactly where you align the text from right to UISearchBar.

Any ideas? Thank!

+5
source share
3 answers

This is what I did:

for (UIView *subView in self.subviews){
        if ([subView isKindOfClass:[UITextField class]]) {
            UITextField *text = (UITextField*)subView;
            text.textAlignment = UITextAlignmentRight;
            text.rightViewMode = UITextFieldViewModeAlways;
        }
    }

If you also want to move the magnifying glass icon, you can do this:

text.leftView = nil;
text.rightView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search_icon.png"]];

But you will need to provide a search_icon.png image.

+6
source

Here is the solution

UITextField *searchTextField = [searchBar valueForKey:@"_searchField"];
UILabel *placeholderLabel = [searchTextField valueForKey:@"_placeholderLabel"];
[placeholderLabel setTextAlignment:NSTextAlignmentLeft];
+3
source

, ...

//Step1 : Make blank attributed string
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:@""];

//Step2 : Append placeholder to blank attributed string
NSString *strSearchHere = @"Search here...";
NSDictionary * attributes = [NSDictionary dictionaryWithObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
NSAttributedString * subString = [[NSAttributedString alloc] initWithString:strSearchHere attributes:attributes];
[attributedString appendAttributedString:subString];

//Step3 : Append dummy text to blank attributed string
NSString *strLongText = @"LongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongText";
NSDictionary * attributesLong = [NSDictionary dictionaryWithObject:[UIColor clearColor] forKey:NSForegroundColorAttributeName];
NSAttributedString * subStringLong = [[NSAttributedString alloc] initWithString:strLongText attributes:attributesLong];
[attributedString appendAttributedString:subStringLong];

//Step4 : Set attributed placeholder string to searchBar textfield
UITextField *searchTextField = [searchBarr valueForKey:@"_searchField"];
searchTextField.attributedPlaceholder = attributedString;
searchTextField.leftView = nil; //To Remove Search icon
searchTextField.textAlignment = NSTextAlignmentLeft;
0

All Articles