以编程方式为UITableViewController设置UIActivityIndicatorView

8

我有一个常规的 UITableViewController,它的唯一视图是一个 UITableView,我希望在表格视图之外添加一个 UIActivittyIndicatorView

所以我需要这样的视图结构:

view (UIView):
  tableView
  activityIndicatorView

没有使用InterfaceBuilder的最简单方法是什么?我猜我需要重写loadView:方法,但到目前为止我还没有成功。
1个回答

28

针对ARC和iOS 5.0+的更新(我认为旧版本需要被移除,因为我们有了新的、更好的API:):

将以下内容添加到您的UIViewController子类的头文件.h中:

 @property (nonatomic, weak) UIActivityIndicator *activityIndicator;

在您的UIViewController子类的.m文件中覆盖方法:

- (void)loadView {
    [super loadView];
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    // If you need custom color, use color property
    // activityIndicator.color = yourDesirableColor;
    [self.view addSubview:activityIndicator];
    [activityIndicator startAnimating];
    self.activityIndicator = activityIndicator;
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    CGSize viewBounds = self.view.bounds;
    self.activityIndicator.center = CGPointMake(CGRectGetMidX(viewBounds), CGRectGetMidY(viewBounds));
} 

非ARC版本,iOS < 5.0:
您应该重写方法。
-(void)loadView {
    [super loadView];
    self.activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
    [self.view addSubview:self.activityIndicator];
    self.activityIndicator.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
    [self.activityIndicator startAnimating];
}

此外,请添加

@property (nonatomic, assign) UIActivityIndicatorView *activityIndicator;

在头文件中,并且。
@synthesize activityIndicator;

到 .m 文件


应该是 CGRect viewBounds = self.view.bounds; 而不是 CGSize viewBounds...,对吗? - wmora

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接