10

在 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;
4

6 回答 6

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

享受 !!

于 2013-10-10T19:29:44.930 回答
3

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

在此处输入图像描述

于 2017-02-01T09:23:55.310 回答
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
    }    
}
于 2016-01-14T07:08:38.400 回答
0

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;
}
于 2013-10-10T15:36:40.063 回答
0

你可以调用这个方法,它看起来像截图: 在此处输入图像描述

+(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];
}
于 2016-10-25T04:36:42.863 回答
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()
    }

}
于 2016-02-29T15:13:15.490 回答