将视图居中在视图控制器的中心

时间:2016-05-23 06:27:51

标签: ios objective-c uiactivityindicatorview

我正在尝试在加载表格视图时显示动画微调器。

loadingView = [[UIView alloc] initWithFrame:CGRectMake(75, 155, 170, 170)];
loadingView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
loadingView.clipsToBounds = YES;
loadingView.layer.cornerRadius = 10.0;

activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityView.frame = CGRectMake(65, 40, activityView.bounds.size.width, activityView.bounds.size.height);
[loadingView addSubview:activityView];

loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 115, 130, 22)];
loadingLabel.backgroundColor = [UIColor clearColor];
loadingLabel.textColor = [UIColor whiteColor];
loadingLabel.adjustsFontSizeToFitWidth = YES;
loadingLabel.textAlignment = NSTextAlignmentCenter;
loadingLabel.text = @"Loading...";
[loadingView addSubview:loadingLabel];

[self.view addSubview:loadingView];
[activityView startAnimating];

我在UIActivityIndicatorView中嵌入了loadingView。 我面临的问题是:

  1. 加载视图不在视图控制器的中心。
  2. 我正在尝试将加载视图置于视图控制器的中心,UIActivityIndicatorView必须位于加载视图的中心,但它并没有像我期望的那样居中。

3 个答案:

答案 0 :(得分:2)

当视图控制器布置子视图时,您应该将其居中。

对于视图控制器,viewDidLayoutSubviews是一个很好的选择:

- (void)viewDidLayoutSubviews {
  [super viewDidLayoutSubviews];
  self.activityView.center = CGPointMake(CGRectGetWidth(self.loadingView.frame) / 2, CGRectGetHeight(self.loadingView.frame) / 2);
  self.loadingView.center = CGPointMake(CGRectGetWidth(self.view.frame) / 2, CGRectGetHeight(self.view.frame) / 2);
}

答案 1 :(得分:1)

设置框架:

int width = 170;
loadingView = [[UIView alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width/2) - (width)/2, ([UIScreen mainScreen].bounds.size.height/2) - (height)/2, width, width)];
activityView.frame = CGRectMake((loadingView.frame.size.width/2) -(activityView.bounds.size.width/2), (loadingView.frame.size.height/2) - (activityView.bounds.size.height/2) - 11, activityView.bounds.size.width, activityView.bounds.size.height);
loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake((loadingView.frame.size.width/2) - 65, loadingView.frame.size.height - 25, 130, 22)];

loadingView.center = CGPointMake(([UIScreen mainScreen] .bounds.size.width / 2),([UIScreen mainScreen] .bounds.size.height / 2));

答案 2 :(得分:0)

在ViewDidLoad中添加以下代码:

[self.view addSubview: loadingView];
loadingView .center = CGPointMake(CGRectGetWidth(self.view.frame) / 2, CGRectGetHeight(self.view.frame) / 2);