用UISearchBar中的Activityindicator替换BookmarkButton

Mon*_*ono 3 iphone uisearchbar

我使用UISearchBar输入地址以建立网络连接.在建立连接时,我想显示活动指示器,而不是搜索栏右侧的微小BookmarkButton.据我所知,没有公开声明的属性可以让我访问搜索栏的正确子视图.我见过这个已经完成了,有什么想法吗?

Joh*_*ger 10

在搜索或连接正在进行时,如何用活动指示器替换左侧的搜索图标?

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)