【问题标题】:How to add Activity Indicator as subview to UIButton?如何将活动指示器作为子视图添加到 UIButton?
【发布时间】:2010-09-08 13:41:48
【问题描述】:

我们可以将活动指示器作为子视图添加到 UIButton 吗?

如果是,请告诉我该怎么做?

我使用了[按钮 addSubview:activityIndi​​cator];

不工作...

【问题讨论】:

  • 什么不起作用?请包括您收到的任何错误消息以及这些对象的声明和实例化方式。另外,你用什么方法调用 addSubview:?
  • 代码正确。请显示更多代码,即如何设置指标?
  • 我在表格视图单元格中添加了“按钮”作为子视图。我想在那个按钮上方显示一个活动指示器,我必须用其他方法来做。我已经在 .h 文件中声明了按钮。
  • 我只想在表格视图的单元格中显示活动指示器来代替按钮...

标签: iphone


【解决方案1】:

我发现将 UIActivityIndi​​catorView 添加到 UIButton 是一种非常有用的方法,它让用户无需使用 MBProgressHUD 就可以知道正在发生的事情(我认为 HUD 非常好,但不应该在所有情况下都使用。

为此我创建了两个函数:

我已经分配了我的 UIButton,所以它是一个名为 _confirmChangesButton 的类变量 然后我创建我的活动指示器,设置它的框架(考虑到按钮大小),然后添加指示器很容易。

- (void)addActivityIndicatorToConfirmButton {

    // Indicator needs to be in the middle of the button. So half the screen less half the buttons left inset less half the activity indicator size
    CGRect rect = CGRectMake([UIScreen mainScreen].bounds.size.width/2 - 10 - 15, 5, 30, 30);

    UIActivityIndicatorView * activity = [[UIActivityIndicatorView alloc] initWithFrame:rect];
    activity.hidesWhenStopped = YES;

    [_confirmChangesButton setTitle:@"" forState:UIControlStateNormal];
    [_confirmChangesButton addSubview:activity];
    [activity startAnimating];
}

如果您使用块,则具有删除功能也很有用。可能是完成任务返回失败,因此我们想要删除指示器并将标题更改回来。在这个函数中,我们需要确保删除指示器而不是按钮标签,这是该按钮上的另一个子视图。

- (void)removeActivityIndicatorFromConfirmButton {

    UIActivityIndicatorView * activity = _confirmChangesButton.subviews.lastObject;;

    [activity removeFromSuperview];

    [_confirmChangesButton setTitle:@"Confirm Change" forState:UIControlStateNormal];
}

我发现使用这两者可以创造更好的用户体验,让用户知道按下按钮时发生了什么。

希望对你有帮助

【讨论】:

  • 是的。这增加了良好的用户体验。我会接受这个作为 ans 以便任何寻找这个查询的用户都可以得到 ans。
【解决方案2】:

使用下面的代码为按钮或任何 uiview 对象添加活动指示器

UIActivityIndicatorView *aView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
aView.frame = CGRectMake(0, 0, {yourButton}.frame.size.width, {yourButton}.frame.size.height);
aView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
[{yourButton} addSubview:aView];
[aView startAnimating];

希望这会有所帮助..

【讨论】:

    【解决方案3】:

    我认为不可能向按钮添加视图。 UIButton 有这个方法是因为它继承自 UIVIew。 真正的问题是:为什么要在按钮上而不是其他地方添加活动指示器?

    【讨论】:

    • 2010 年是否有可能我不知道,但现在肯定有可能并且非常有用。向 uibutton 添加一个活动指示器可以让用户知道该按钮已被按下,即使在某些事情发生之前有一点延迟。
    【解决方案4】:

    你做了[activityIndi​​cator startAnimating];另外,当您在 tableview 中使用它时,只需检查标签是否设置正确

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      • 2015-02-17
      • 1970-01-01
      相关资源
      最近更新 更多