UISearchBar 搜索图标在 iOS7 中没有左对齐

Posted

技术标签:

【中文标题】UISearchBar 搜索图标在 iOS7 中没有左对齐【英文标题】:UISearchBar search icon isnot left aligned in iOS7 【发布时间】:2013-10-10 07:17:04 【问题描述】:

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;

【问题讨论】:

【参考方案1】:

无法更改搜索栏占位符文本的对齐方式,我尝试了这么多“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             ";
  

尽情享受吧!

【讨论】:

占位符文本不固定怎么办? @jAckOdE 使用此方法获取字符串大小sizeWithFont: constrainedToSize: lineBreakMode: 此方法用于计算文本的大小,在我的情况下它需要反向计算:确定适合大小的文本字符串。 AFAIK,没有直接的方法,但我认为我们可以进行循环并增加尾随空格的数量,直到字符串适合文本字段的大小。虽然这不是一个很好的解决方案 @kmithi 您是否提交了包含此代码的应用程序?批准了吗?【参考方案2】:

在 Swift-3 中:-

放大图标可以通过在 searchBar 上添加子视图并取消默认放大图标来左对齐。

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)
        
    

【讨论】:

【参考方案3】:

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

【讨论】:

【参考方案4】:

1 个子类 uitextField

2 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个包含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;

【讨论】:

【参考方案5】:

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


【讨论】:

【参考方案6】:

你可以调用这个方法,它看起来像截图:

+(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];

【讨论】:

以上是关于UISearchBar 搜索图标在 iOS7 中没有左对齐的主要内容,如果未能解决你的问题,请参考以下文章

iOS 7 UISearchBar 右间距

如何在 iOS 7 的 UISearchBar 中更改位置或隐藏放大镜图标?

在 iOS7 中将搜索栏与导航栏结合时 UISearchbar 空间为空?

iOS7 中 UISearchBar 和 UITableView 的问题

字段为空时为 UISearchBar 启用“搜索”按钮? (IOS 7)

在 iOS7 中移除 UISearchBar 的边框