从 UIButton 视图中删除 Activity Indicator 子视图

Posted

技术标签:

【中文标题】从 UIButton 视图中删除 Activity Indicator 子视图【英文标题】:Remove Activity Indicator subview from UIButton view 【发布时间】:2015-11-13 17:15:41 【问题描述】:

我用几个按钮构建了一个界面。这些按钮从互联网上提取信息以获得它们的标题。我向视图中的每个按钮添加了一个 UIActivityIndi​​cator,如下所示:

- (void) addActivityIndicator 
    UIButton * button;

    for (int i = 1; i <= 10; i++)
        button = (UIButton *)[self viewWithTag:i];
        NSLog(@"Button: %i",i);
        [button setTitle:@"" forState:UIControlStateNormal];
        button.enabled = NO;

         UIActivityIndicatorView * buttonSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [buttonSpinner startAnimating];
        buttonSpinner.tag = i;
        buttonSpinner.frame = button.bounds;
        [button addSubview:buttonSpinner];
    


但是,我似乎无法访问个别指标来删除它们。

[(UIButton *)[self viewWithTag:tag] setTitle:[NSString stringWithFormat:@"%@",[self addTitle:i]] forState:UIControlStateNormal];
[(UIButton *)[self viewWithTag:tag] setEnabled:YES];
[(UIButton *)[self viewWithTag:tag] [buttonSpinner stopAnimating]];

有什么想法吗?

【问题讨论】:

【参考方案1】:
    for (int i = 1; i <= 10; i++)
        button = (UIButton *)[self viewWithTag:i];
        NSLog(@"Button: %i",i);
        [button setTitle:@"" forState:UIControlStateNormal];
        button.enabled = NO;

         UIActivityIndicatorView * buttonSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [buttonSpinner startAnimating];
        buttonSpinner.tag = i*99;
        buttonSpinner.frame = button.bounds;
        [button addSubview:buttonSpinner];
    

然后,获取UIActivityIndicatorView

[(UIActivityIndicatorView *)[(UIButton *)[self viewWithTag:tag] viewWithTag:tag] stopAnimating];

【讨论】:

是的,我之前尝试过,但收到错误[UIButton stopAnimating]: unrecognized selector sent to instance 是的。我认为存在按钮标签和指示器标签相同的问题。 我不认为因为它们是相同的。您是否成功更改了按钮的标题? 我发现如果UIButtons的标签和UIActivityIndi​​catorView的标签是一样的,你的方法就失败了。但是,如果更改指示器视图的标记(示例标记*99),那么您的方法可以正常工作。 @@!。无论如何,问题已解决。太奇怪了。【参考方案2】:

也许您可以尝试遍历子视图并将其删除?

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

UIActivityIndicatorView *toRemove;
for (UIView *view in button.subviews)

    if ([view isKindOfClass:[UIActivityIndicatorView class]])
    
        toRemove = (UIActivityIndicatorView *)view;
        break;
    

[toRemove removeFromSuperview];

【讨论】:

以上是关于从 UIButton 视图中删除 Activity Indicator 子视图的主要内容,如果未能解决你的问题,请参考以下文章

删除动态创建的 UIButton 子视图

从其他 ViewController 中删除带有标签的视图

Swift 3 - 自定义 UIButton 半径删除约束?

从 Activity 访问 Fragment 中的视图绑定

以编程方式从其父视图中删除子视图并将其附加到其他父视图

移除 UIButton 的手势