Replace BookmarkButton with Activityindicator in UISearchBar

iphone, uisearchbar

Solution

How about replacing the search icon on the left side with an activity indicator while searches or connections are in progress?

SearchBarWithActivity.h:

#import <UIKit/UIKit.h>

@interface SearchBarWithActivity : UISearchBar

- (void)startActivity;  // increments startCount and shows activity indicator
- (void)finishActivity; // decrements startCount and hides activity indicator if 0

@end

SearchBarWithActivity.m:

#import "SearchBarWithActivity.h"

@interface SearchBarWithActivity()

@property(nonatomic) UIActivityIndicatorView *activityIndicatorView;
@property(nonatomic) int startCount;

@end


@implementation SearchBarWithActivity

- (void)layoutSubviews {
    UITextField *searchField = nil;

    for(UIView* view in self.subviews){
        if([view isKindOfClass:[UITextField class]]){
            searchField= (UITextField *)view;
            break;
        }
    }

    if(searchField) {
        if (!self.activityIndicatorView) {
            UIActivityIndicatorView *taiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            taiv.center = CGPointMake(searchField.leftView.bounds.origin.x + searchField.leftView.bounds.size.width/2,
                                      searchField.leftView.bounds.origin.y + searchField.leftView.bounds.size.height/2);
            taiv.hidesWhenStopped = YES;
            taiv.backgroundColor = [UIColor whiteColor];
            self.activityIndicatorView = taiv;
            [taiv release];
            _startCount = 0;

            [searchField.leftView addSubview:self.activityIndicatorView];
        }
    }

    [super layoutSubviews];
}

- (void)startActivity  {
    self.startCount = self.startCount + 1;
}

- (void)finishActivity {
    self.startCount = self.startCount - 1;
}

- (void)setStartCount:(int)startCount {
    _startCount = startCount;
    if (_startCount > 0)
        [self.activityIndicatorView startAnimating];
    else {
        [self.activityIndicatorView stopAnimating];
    }
}

@end

Problem

I use a UISearchBar for entering an address to establish a network connection. While the connection is made I want to show the activity indicator instead of the tiny BookmarkButton on the right side of the searchbar. As far as I can see there is no public declared property that would give me access to the correct subview of the searchbar. I have seen this been done, any thoughts?

Original source