如何为每个单元添加UIActivity指示器并保持对每个单独指示器的控制

我正在尝试在我的UITableView中的某些单元格中添加一个活动指示器。 我在方法didSelectRowAtIndexpath中成功地使用了

CGRect CellFrame = CGRectMake(260, 10, 20, 20); actindicator = [[UIActivityIndicatorView alloc]initWithFrame:CellFrame]; [actindicator setHidesWhenStopped:NO]; [actindicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray]; actindicator.tag =1; [[cell contentView] addSubview:actindicator]; 

我需要从另一种方法控制这些多活动指标。 我认为属性是一种方法来做到这一点,但每次初始化一个新的actIndicator实例,我将参考文献放在活动指示符的“最新”初始化之外,这意味着我只能控制一个。

我需要做什么(如果可能的话?)来保持对所有actIndicators的引用,这样我就可以开始动画所有这些动作了吗? 或者我可以以某种方式使用actindicator.tag来控制某种forms的引用。

非常感谢任何帮助。

编辑:(来自答案)访问tableView中标记为1的所有活动实例指标(仅限可见单元格)可以使用下面的另一种方法:

 for (UITableViewCell *cell in [self.tableView visibleCells]) { UIActivityIndicatorView *actView = (UIActivityIndicatorView *)[cell.contentView viewWithTag:1]; [actView startAnimating]; activityFlag = 1; } 

上述方法将遍历所有可见单元格并开始为活动指示器设置动画。

为了处理滚动的tableview的情况,我使用下面的方法重新设置指标的动画,该方法位于cellForRowAtIndexPath中。 cellStateKey只是指示单元格旁边是否有复选标记,如果它有一个复选标记并且我的activityflag(正在进行异步网络服务器调用)已设置..那我想继续动画。(技术上重新启动动画,作为滚动tableview停止它)

 if ([[rowData objectForKey:cellStateKey] boolValue]) { cell.accessoryType = UITableViewCellAccessoryCheckmark; if(cell.accessoryType == UITableViewCellAccessoryCheckmark &&activityFlag ==1){ for (UIView *sub in [[cell contentView] subviews]) { if (sub.tag == 1) { UIActivityIndicatorView *acView = (UIActivityIndicatorView *) [cell.contentView viewWithTag:1]; [acView startAnimating]; } } 

如原始问题中所述,我在方法didSelectRowAtIndexPath中初始化我的活动指标(并在必要时删除活动指标)

一个简单的方法(假设您在代码中添加指示符)是首先通过调用[tableView visibleCells]表中可见单元格(或行)的集合。 然后像这样遍历单元格:

 for (UITableViewCell *cell in [tableView visibleCells]) { for (UIView *sub in [cell subViews]) { if (sub.tag == 1) { // "1" is not a good choice for a tag here UIActivityIndicatorView *act = (UIActivityIndicatorView *)sub; [act startAnimating]; // or whatever the command to start animating is break; } } } 

您需要处理的复杂性更高:在原始代码中,您需要确保每次调用cellForRowAtIndexPath都不会向预先存在的单元格添加其他活动指示符,并且您需要考虑到用户可能稍后滚动表格,暴露未启用其活动指示符的单元格。

您可以将UIActivityIndi​​catorView添加为单元格的accessoryView。

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; spinner.frame = CGRectMake(0, 0, 24, 24); UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; cell.accessoryView = spinner; [spinner startAnimating]; [spinner release]; } 

您需要通过扩展它来创建自定义UITableViewCell。 然后将UIActivityIndi​​catorView作为该Cell的成员。 然后,您可以访问它并逐个单元地控制它。

假设活动视图指示符标记在cell.contentView中是唯一的,您可以尝试以下方法:

 UITableViewCell *cell = [tableview cellForRowAtIndexPath:indexpath]; UIActivityIndicatorView *acView = (UIActivityIndicatorView *)[cell.contentView viewWithTag:1]; //acView will be your activitivyIndicator