【问题标题】:How to access a UIActivityIndicatorView in a UITableView's section header view?如何在 UITableView 的部分标题视图中访问 UIActivityIndi​​catorView?
【发布时间】:2010-01-13 21:43:29
【问题描述】:

我想用我的 UITableView 做一些非常简单的事情:我想将一个 UIActivityIndi​​catorView 添加到一个部分的标题视图中,并让它在我想要的时候动画或消失。

我使用 tableView:viewForHeaderInSection 将 UIActivityIndi​​catorView 添加到标题视图没有问题:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 60.0)];

// create the title
UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(15.0, 12.0, 310.0, 22.0)];
headerLabel.text = @"some random title here";

[customView addSubview:headerLabel];
[headerLabel release];

// Add a UIActivityIndicatorView in section 1
if(section == 1)
{
    [activityIndicator startAnimating];
    [customView addSubview:activityIndicator];
}

return [customView autorelease];

}

activityIndi​​cator 是我的控制器类的属性。 我在 viewDidLoad 方法中分配它:

- (void)viewDidLoad 
{ 
(...)
activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(200, 10, 25, 25)];
}

这样我可以随时向它发送消息(例如 -startAnimating 或 -stopAnimating)。 问题是,一旦我滚动 tableView,activityIndi​​cator 就会消失(我猜是因为 tableView:viewForHeaderInSection: 方法被第二次调用)。

我怎样才能将 activityIndi​​catorView 添加到部分的标题视图中,并且之后仍然能够向它发送消息? (当然,当我向下滚动时,activityIndi​​cator 不会消失)

非常感谢!

【问题讨论】:

    标签: iphone uitableview


    【解决方案1】:

    如果您尝试在多个地方使用相同的活动指示器,那么它可能会从一个地方移动到另一个地方。我相信每个部分标题都需要一个不同的标题。您可能希望使用 MutableArray 来跟踪您创建的标题视图,以便在您在数组中找到没有超级视图的标题视图时可以重用它们,有点像出队和重用单元格。

    这只是一个猜测,因为我没有这样做,但我很确定问题是试图在多个地方重用相同的视图。

    【讨论】:

    • 我不想在多个地方有一个activityIndi​​cator,只在一个地方。
    • 嗯,这就是你想要做的事情,因为我无法想象有任何其他理由继续将子视图添加到同一个视图中
    【解决方案2】:

    问题似乎是由于每次调用 tableView:viewForHeaderInSection: 时重新创建 customView 并将 activityIndi​​cator 添加为子视图引起的。

    不使用子视图帮助我解决了这个问题:

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
    
    // Add a UIActivityIndicatorView in section 1
    if(section == 1)
    {
        [activityIndicator startAnimating];
        return activityIndicator;
    }
    
        UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 60.0)];
    
    // create the title
    UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(15.0, 12.0, 310.0, 22.0)];
    headerLabel.text = @"some random title here";
    
    [customView addSubview:headerLabel];
    [headerLabel release];
    
    
    return [customView autorelease];
    }
    

    (虽然看起来很丑,activityIndi​​cator 占据了该部分的整个宽度。我最好为第 1 部分创建一个独特的 customView,并将 activityIndi​​cator 作为一个子视图一劳永逸地添加)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      相关资源
      最近更新 更多