Removing the image on the left of an UISearchbar

前端 未结 17 1601
攒了一身酷
攒了一身酷 2020-12-29 20:44

Can I remove the image on the left of an UISearchbar and add a new image?

相关标签:
17条回答
  • 2020-12-29 21:02

    For a specific UISearchBar instance.

    Objective-C:

    // Get the inner search field.
    UITextField *searchField = (UITextField *)[searchBar valueForKey:@"searchField"];
    
    // Hide the left search icon.
    [searchField setLeftViewMode:UITextFieldViewModeNever];
    
    0 讨论(0)
  • 2020-12-29 21:04
    // hide magnifying glass
        UITextField* searchField = nil;
        for (UIView* subview in searchBar.subviews) {
            if ([subview isKindOfClass:[UITextField class]]) {
                searchField = (UITextField*)subview;
                break;
            }
        }
        if (searchField) {
            searchField.leftViewMode = UITextFieldViewModeNever;
        }
    

    This hides magnifying glass. Works well.

    0 讨论(0)
  • 2020-12-29 21:06

    In iOS 5.0+, you can customize the search bar image using

    - (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state
    

    in a specific instance of a UISearchBar or across a bunch using the UIAppearance proxy.

    0 讨论(0)
  • 2020-12-29 21:06

    In swift 2.0 do this:

    let textFieldInsideSearchBar = self.searchBar.valueForKey("searchField") as! UITextField
    textFieldInsideSearchBar.leftViewMode = UITextFieldViewMode.Never
    
    0 讨论(0)
  • 2020-12-29 21:11

    To completely remove the icon, you can use the following lines of code:

    Objective-C:

    // Remove the icon, which is located in the left view
    [UITextField appearanceWhenContainedIn:[UISearchBar class], nil].leftView = nil;
    
    // Give some left padding between the edge of the search bar and the text the user enters
    [UISearchBar appearance].searchTextPositionAdjustment = UIOffsetMake(10, 0);
    

    Swift:

    // Remove the icon, which is located in the left view
    UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).leftView = nil
    
    // Give some left padding between the edge of the search bar and the text the user enters
    UISearchBar.appearance().searchTextPositionAdjustment = UIOffsetMake(10, 0)
    
    0 讨论(0)
  • 2020-12-29 21:12

    Replace the search bar icon with a 1x1 transparent image and offset the text position

    UIImage *blank = [UIImage imageNamed:@"blank"];
    [self.searchBar setImage:blank forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    self.searchBar.searchTextPositionAdjustment = UIOffsetMake(-19, 0);
    
    0 讨论(0)
提交回复
热议问题