日々精進

新しく学んだことを書き留めていきます

UISearchBarの中のTextFieldの背景色を変更する

  • UISearchBarのsearchBarStyleをminimalにする。
  • UISearchBarを持つViewControllerで以下を実装する
- (void)viewDidLoad
{
    [super viewDidLoad];
    UITextField *textField = [self findTextFieldOfSearchBar:self.searchBar];
    // 背景色を白に変更
    [textField setBackground:[self imageWithColor:[UIColor whiteColor] rect:self.searchBar.bounds]];
    [textField setBorderStyle:UITextBorderStyleNone];
    textField.layer.cornerRadius = 5;
}

- (UITextField *)findTextFieldOfSearchBar:(UIView *)searchBar
{
    for (UIView *view in searchBar.subviews) {
        if ([view isKindOfClass:[UITextField class]]) {
            return (UITextField *) view;
        } else {
            UITextField *textField = [self findTextFieldOfSearchBar:view];
            if (textField) {
                return textField;
            }
        }
    }
    return nil;
}

- (UIImage *)imageWithColor:(UIColor *)color rect:(CGRect)rect {
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

なんかもっと楽な方法ありそうな気がするが・・・てかUISearchBarのメソッドで変えられるようにしてほしい。。 UISearchBarはデザインの自由度が低い感じだなあ。

参考: