How to change UISearchBar Placeholder and image tint color?

前端 未结 12 2368
暖寄归人
暖寄归人 2020-11-29 01:24

I\'ve been trying search results for hours, but I can\'t get this figured out. Perhaps it isn\'t possible. I\'m trying to change the tint color of the placeholder text and m

12条回答
  •  爱一瞬间的悲伤
    2020-11-29 02:18

    Just found this thread, sorry about the bump given the age. However it helped me in trying to fix my issue, and adding onto @m_katsifarakis answer, I added more to his existing category.

    Adding additional color + font support for both placeholder and input text.

    Only tested on iOS 13 as that's all I am supporting.

    @interface UISearchBar (ColorandFont)
    - (void)setPlaceholderColor:(UIColor *)placeholderColor setPlaceholderFont:(UIFont *)placeholderFont;
    - (void)setTextColor:(UIColor *)textColor setTextFont:(UIFont *)textFont;
    @end
    @implementation UISearchBar (ColorandFont)
    
    //Placeholder Color
    - (void)setPlaceholderColor:(UIColor *)placeholderColor setPlaceholderFont:(UIFont *)placeholderFont{
        UILabel *labelView = [self placeholderText:self];
        [labelView setTextColor:placeholderColor];
        [labelView setFont:placeholderFont];
    }
    - (UILabel *)placeholderText:(UIView *)view {
        for (UIView *v in [view subviews]) {
            if ([v isKindOfClass:[UILabel class]]) {
                return (UILabel *)v;
            }
    
            UIView *labelView = [self placeholderText:v];
            if (labelView) {
                return (UILabel *)labelView;
            }
        }
        return nil;
    }
    
    //Text Color
    - (void)setTextColor:(UIColor *)textColor setTextFont:(UIFont *)textFont{
        UITextField *textView = [self searchBarText:self];
        [textView setTextColor:textColor];
        [textView setFont:textFont];
    }
    - (UITextField *)searchBarText:(UIView *)view {
        for (UIView *v in [view subviews]) {
            if ([v isKindOfClass:[UITextField class]]) {
                return (UITextField *)v;
            }
    
            UIView *textView = [self searchBarText:v];
            if (textView) {
                return (UITextField *)textView;
            }
        }
        return nil;
    }
    @end
    

    Usage (I used in viewDidLoad and Appear) given my current setup, results may vary:

    [self.searchBar setPlaceholderColor:[UIColor lightTextColor] setPlaceholderFont:[UIFont italicSystemFontOfSize:13]];
    [self.searchBar setTextColor:[UIColor whiteColor] setTextFont:[UIFont systemFontOfSize:16]];
    

提交回复
热议问题