UISearchBar搜索图标在iOS7中未对齐

时间:2013-10-10 07:17:04

标签: iphone ios objective-c ios7 uisearchbar

在iOS7中,搜索图标和占位符文本总是出现在中间。我尝试将搜索栏中文本字段的文本对齐方式更改为左边但是它不起作用。 有没有办法让搜索栏搜索图标在iOS7中显示为左对齐

我尝试了以下几行,但它不起作用:

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 个答案:

答案 0 :(得分:20)

没有办法改变搜索栏的占位符文本的对齐方式,我尝试了很多“SO”答案,但没有人工作。最后,我结束了这个解决方法

在占位符文字右侧添加一些空格

    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             ";
  }

享受!!

答案 1 :(得分:2)

在Swift-3中: -

通过在searchBar上添加子视图并使默认的Magnify图标无效,可以将放大图标左对齐。

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

答案 2 :(得分:1)

这不是一个好的解决方案,但它有效。 (在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
    }    
}

答案 3 :(得分:0)

1个子类uitextField

initWithFrame中的

2

  [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包括UItextfieldDelegate,并实现以下委托方法

- (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;
}

答案 4 :(得分:0)

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()
    }

}

答案 5 :(得分:0)

您可以调用此方法,它看起来像截图: 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];
}