4

我有一个带有通用圆形矩形按钮的视图,该按钮可以连接到另一个视图。当用户按下圆角矩形时,它会开始获取。在处理提取时,我想让一个旋转的轮子替换圆角矩形按钮内的文本(“下一步”)。

我创建了微调器:

UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[spinner startAnimating];

但我不知道如何让它替换圆角矩形按钮中的文本。

有什么建议吗?谢谢你。

4

2 回答 2

7

像往常一样创建(或获取对)按钮的引用,然后在处理按钮单击时,创建微调器并将其设置为按钮的子视图。禁用按钮以停止多次点击可能也值得。

以下几行应该可以解决问题:

  ...
  UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  button.frame = CGRectMake(10, 10, 70, 40);
  [button setTitle:@"Next" forState:UIControlStateNormal];
  [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:button];
  ...

- (void)click:(UIButton *)button {
  [button setTitle:@"" forState:UIControlStateNormal];
  UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  [spinner startAnimating];
  spinner.frame = button.bounds;
  [button addSubview:spinner];
  button.enabled = NO;

  // do your actual work...
}
于 2012-07-08T07:34:22.450 回答
1

我写了一个利用关联对象的类别

UIButton+ActivityIndi​​cator.h

// Created by reynaldo on 1/16/14.

#import <Foundation/Foundation.h>

@interface UIButton (ActivityIndicator)
- (void)startActivityIndicator;
- (void)stopActivityIndicator;
@end

UIButton+ActivityIndi​​cator.m

// Created by reynaldo on 1/16/14.

#import <objc/runtime.h>
#import "UIButton+ActivityIndicator.h"

static char TITLE_KEY;
static char ACTIVITY_INDICATOR_KEY;

@implementation UIButton (ActivityIndicator)

- (void)startActivityIndicator {
    objc_setAssociatedObject(self, &TITLE_KEY, self.currentTitle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    [self setTitle:@"" forState:UIControlStateNormal];
    UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    [self addSubview:activityIndicatorView];
    activityIndicatorView.frame = CGRectMake(self.frame.size.width / 2, self.frame.size.height / 2. - 2, 7, 7);
    [activityIndicatorView startAnimating];

    objc_setAssociatedObject(self, &ACTIVITY_INDICATOR_KEY, activityIndicatorView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

- (void)stopActivityIndicator {
    NSString *title = objc_getAssociatedObject(self, &TITLE_KEY);
    UIActivityIndicatorView *activityIndicatorView = objc_getAssociatedObject(self, &ACTIVITY_INDICATOR_KEY);

    if(activityIndicatorView) {
        [activityIndicatorView removeFromSuperview];
    }

    if(title.length) {
        [self setTitle:title forState:UIControlStateNormal];
    }
}

@end
于 2014-01-16T19:24:10.647 回答