showing activity indicator in Table cells

本文介绍两种在iOS TableView单元格中显示UIActivityIndicatorView的方法。一种是作为附属视图显示在单元格右侧;另一种则是子视图形式,允许更灵活地控制位置和大小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 deselectRowAtIndexPath:[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];
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值