ollowing are two ways to display UIActivityIndicatorViews in a cell of a table view (UITableView). The first will add a spinner as an accessory view, which will display the spinner on the right of the cell. The second approach will add a spinner as a subview
in the cell. The primary advantage of using a custom view is that you can display the spinner wherever you like in the cell.
UIActivityIndicator as Accessory View
The example below will add an accessory view when a row is selected through the didSelectRowAtIndexPath method.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIActivityIndicatorView *activityView =
[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[activityView startAnimating];
[cell setAccessoryView:activityView];
[activityView release];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}
The spinner in this case appears on the far right of the cell:
UIActivityIndicator as SubView
When using a subview we have more control over size and location of the spinner. In this example I center the spinner vertically and append it at the end of the cell text:
#define SPINNER_SIZE 25
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
// Get center of cell (vertically)
int center = [cell frame].size.height / 2;
// Size (width) of the text in the cell
CGSize size = [[[cell textLabel] text] sizeWithFont:[[cell textLabel] font]];
// Locate spinner in the center of the cell at end of text
[spinner setFrame:CGRectMake(size.width + SPINNER_SIZE, center - SPINNER_SIZE / 2, SPINNER_SIZE, SPINNER_SIZE)];
[[cell contentView] addSubview:spinner];
[spinner startAnimating];
[spinner release];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}