Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace the text in a round rect button with a spinner?

I have a view with a generic rounded rect button that segues to another view. When users press the rounded rect it starts a fetch. I would like to have a spinning wheel replace the text ("Next") inside the rounded rect button while the fetch is processed.

I created the spinner:

UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[spinner startAnimating];

But I don't know how to make it replace the text in the rounded rect button.

Any suggestion? Thank you.

like image 992
blrsk Avatar asked Feb 19 '23 22:02

blrsk


1 Answers

Create (or get a reference to) the button as usual, then, while handling the button click, create your spinner and set it as a subview of the button. It's probably also worth disabling the button to stop multiple clicks.

Something along the following lines should do the trick:

  ...
  UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  button.frame = CGRectMake(10, 10, 70, 40);
  [button setTitle:@"Next" forState:UIControlStateNormal];
  [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:button];
  ...

- (void)click:(UIButton *)button {
  [button setTitle:@"" forState:UIControlStateNormal];
  UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  [spinner startAnimating];
  spinner.frame = button.bounds;
  [button addSubview:spinner];
  button.enabled = NO;

  // do your actual work...
}
like image 170
Martin Kenny Avatar answered Apr 29 '23 09:04

Martin Kenny