Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up an UIActivityIndicatorView for the UITableViewController programmatically

I have a regular UITableViewController and a UITableView as its only view, and I want to have an UIActivittyIndicatorView in addition to the table view.

So I need a view structure like this:

view (UIView):
  tableView
  activityIndicatorView

What's the cleanest way to do it without InterfaceBuilder? I guess I need to override the loadView: method, but I haven't succeed doing it so far.

like image 593
Dmitry Sokurenko Avatar asked Mar 23 '12 15:03

Dmitry Sokurenko


1 Answers

UPDATE for ARC and iOS 5.0+ (I think old version needs to be removed already as we have new, better API's:)):

Add to header .h file of your UIViewController subclass:

 @property (nonatomic, weak) UIActivityIndicator *activityIndicator;

And override methods in .m file of your UIViewController subclass:

- (void)loadView {
    [super loadView];
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    // If you need custom color, use color property
    // activityIndicator.color = yourDesirableColor;
    [self.view addSubview:activityIndicator];
    [activityIndicator startAnimating];
    self.activityIndicator = activityIndicator;
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    CGSize viewBounds = self.view.bounds;
    self.activityIndicator.center = CGPointMake(CGRectGetMidX(viewBounds), CGRectGetMidY(viewBounds));
} 

=============================================================

non-ARC version, iOS < 5.0:

You should override method

-(void)loadView {
    [super loadView];
    self.activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
    [self.view addSubview:self.activityIndicator];
    self.activityIndicator.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
    [self.activityIndicator startAnimating];
}

Also, add

@property (nonatomic, assign) UIActivityIndicatorView *activityIndicator;

at the header file

and

@synthesize activityIndicator;

to the .m file

like image 82
Alexander Tkachenko Avatar answered Sep 18 '22 04:09

Alexander Tkachenko