Styling the cancel button in a UISearchBar

前端 未结 21 1428
-上瘾入骨i
-上瘾入骨i 2020-12-02 09:13

I have a UISearchBar that has a cancel button (it\'s displayed using -(void)setShowsCancelButton:animated). I\'ve changed the tintColor of the sear

21条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 10:02

    After you've initialized your UISearchBar, you can probe into it's subviews and customize each of them. Example:

    for (UIView *view in searchBar.subviews) {
    
        //if subview is the button
        if ([[view.class description] isEqualToString:@"UINavigationButton"]) {
    
            //change the button images and text for different states
            [((UIButton *)view) setEnabled:YES];
            [((UIButton *)view) setTitle:nil forState:UIControlStateNormal];
            [((UIButton *)view) setImage:[UIImage imageNamed:@"button image"] forState:UIControlStateNormal];
            [((UIButton *)view) setBackgroundImage:[UIImage imageNamed:@"button"] forState:UIControlStateNormal];
            [((UIButton *)view) setBackgroundImage:[UIImage imageNamed:@"button_pressed"] forState:UIControlStateSelected];
            [((UIButton *)view) setBackgroundImage:[UIImage imageNamed:@"button_pressed"] forState:UIControlStateHighlighted];
    
        //if the subview is the background
        }else if([[view.class description] isEqualToString:@"UISearchBarBackground"]) {
    
            //put a custom gradient overtop the background
            CAGradientLayer *gradient = [CAGradientLayer layer];
            gradient.frame = view.bounds;
            gradient.colors = [NSArray arrayWithObjects:(id)[[some uicolor] CGColor], (id)[[another uicolor] CGColor], nil];
            [view.layer insertSublayer:gradient atIndex:0];
    
        //if the subview is the textfield
        }else if([[view.class description] isEqualToString:@"UISearchBarTextField"]){
    
            //change the text field if you wish
    
        }
    
    }
    

    Worked out great for me! Especially the gradient :)

提交回复
热议问题