10
votes

In iOS7 the search icon and place holder text are always appearing in middle.I tried changing the text alignment of the text field in search bar to left but it didn't work. Is there any way to make the searchbar search icon appear left aligned in iOS7

I tried the following lines but it did not work:

UITextField *txfSearchField = [_searchBar valueForKey:@"_searchField"];
txfSearchField.textAlignment = NSTextAlignmentLeft;

[_searchArticle setImage:image forSearchBarIcon:UISearchBarIconSearch    state:UIControlStateNormal];
UIimageView *im = [UIImageView alloc]init];
im.image = image;
txfSearchField.leftView =im;
6

6 Answers

20
votes

There is no way to change the alignment of search bar's placeholder text, I tried so many "SO" answer but no one was working. Finally I ended with this workaround

Give some white space in right of placeholder text

    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
        // Load resources for iOS 6.1 or earlier
        self.searchBar.placeholder = @"hello";
   } else {
       // Load resources for iOS 7 or later
       self.searchBar.placeholder = @"hello             ";
  }

Enjoy !!

3
votes

In Swift-3 :-

Magnify icon can be Left alignment by adding the subview over searchBar and nullify default Magnify icon.

let width = 20
let height = 20
func changeSearchBarIcon() {
        let topView: UIView = searchBar.subviews[0] as UIView
        var searchField:UITextField!
        for subView in topView.subviews {
            if subView is UITextField {
                searchField = subView as! UITextField
                break
            }
        }

        if ((searchField) != nil) {
            let leftview = searchField.leftView as! UIImageView
            let magnifyimage = leftview.image
            let imageView  = UIImageView(frame: CGRect(x: searchBar.frame.origin.x  , y:  10, width: width, height: height ) )
            imageView.image = magnifyimage

            searchField.leftView = UIView(frame: CGRect(x: 0 , y: 0, width: width, height: height) )
            searchField.leftViewMode = .always
            searchField.superview?.addSubview(imageView)
        }
    }

enter image description here

1
votes

This is not a good solution but it works. (Test on iOS 9)

import UIKit

class MySearchBar: UISearchBar {

    override func layoutSubviews() {
        super.layoutSubviews()
        if let l = getTextFieldLabel() {
            l.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
        }
        if let i = getIcon() {
            i.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
        }
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context:     UnsafeMutablePointer<Void>) {

        if let l = object as? UILabel {
            l.removeObserver(self, forKeyPath: "frame")
            l.frame = CGRect(x: 29, y: 1, width: 323, height: 25)
            l.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
        }

        if let i = object as? UIImageView {
            i.removeObserver(self, forKeyPath: "frame")
            i.frame = CGRect(x: 8, y: 7.5, width: 13, height: 13)
            i.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
        }
    }

    func getTextFieldLabel() -> UILabel? {
        for v in self.allSubViews(self) {
            if NSStringFromClass(v.dynamicType) == "UISearchBarTextFieldLabel" {
                return v as? UILabel
            }
        }
        return nil
    }

    func getIcon() -> UIImageView? {
        for v in self.allSubViews(self) {
            if NSStringFromClass(v.dynamicType) == "UIImageView" {
                return v as? UIImageView
            }
        }
        return nil
    }

    func allSubViews( v : UIView!) -> [UIView] {
        var views : [UIView] = []
        views += v.subviews
        for s in v.subviews {
            views += allSubViews(s)
        }
        return views
    }    
}
0
votes

1 subclass a uitextField

2 in initWithFrame

  [self setBackgroundColor:[UIColor clearColor]];
        [self setTextAlignment:NSTextAlignmentLeft];
        [self setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
        [self setAutocorrectionType:UITextAutocorrectionTypeNo];
        [self setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        [self setPlaceholder:@"Search"];
        [self setLeftView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search-icon"]]];
        [self setLeftViewMode:UITextFieldViewModeAlways];

3 in main class include UItextfieldDelegate and implement following delegate method

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSString* searchString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    searchYourFriendsArray = [[NSMutableArray alloc] init];

    if(searchString.length > 0 )
    {
        NSMutableArray *searchArray = [NSMutableArray arrayWithArray:yourFriendsArray];
        NSPredicate *predicate  = [NSPredicate predicateWithFormat:@"FirstName beginswith[C] %@ OR LastName beginswith[C] %@",searchString,searchString];
        searchYourFriendsArray  = [NSMutableArray arrayWithArray:[searchArray filteredArrayUsingPredicate:predicate]];

       }

    return YES;
}
0
votes

Workaround for iOS 9:

extension ViewController: UISearchBarDelegate {

    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
        if let searchTextField = searchBar.valueForKey("_searchField") as? UITextField {
            if let placeholderLabel = searchTextField.valueForKey("_placeholderLabel") as? UILabel {
                if searchTextField.textColor == placeholderLabel.textColor {
                    searchTextField.text = ""
                    searchTextField.textColor = UIColor.blackColor()
                    searchTextField.clearButtonMode = .Always
                }
            }
        }
        return true
    }

    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        if searchBar.text == "" {
            if let searchTextField = searchBar.valueForKey("_searchField") as? UITextField {
                if let placeholderLabel = searchTextField.valueForKey("_placeholderLabel") as? UILabel {
                    searchBar.text = "Placeholder"
                    searchTextField.textColor = placeholderLabel.textColor
                    searchTextField.clearButtonMode = .Never
                }
            }
        }
        searchBar.resignFirstResponder()
    }

}
0
votes

You can call this method, and it looks like screenshot: enter image description here

+(void)customizeDisplayForSeachbar:(UISearchBar *)searchBar
{ 
   searchBar.barTintColor = [UIColor whiteColor];
   searchBar.layer.borderWidth = 0.0;
   searchBar.layer.borderColor = [UIColor clearColor].CGColor;

    UITextField *txfSearchField = [searchBar valueForKey:@"_searchField"];
    UIImage *imageIcon=[UIImage imageNamed:@"search_icon.png"];
    float iconWidth=14;
    UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(15, (txfSearchField.superview.frame.size.height-iconWidth)/2-1, iconWidth, iconWidth)];
    imgView.contentMode=UIViewContentModeScaleAspectFit;
    imgView.image=imageIcon;
    txfSearchField.leftView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];
    txfSearchField.leftViewMode=UITextFieldViewModeAlways;
    [txfSearchField.superview addSubview:imgView];
}