2016-05-23 34 views
1

我試圖在加載表視圖時顯示一個動畫微調框。在視圖控制器的中心居中視圖

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]; 

我已經嵌入loadingView一個UIActivityIndicatorView。 我面臨的問題是:

  1. 加載視圖不在視圖控制器的中心。
  2. 我試圖將加載視圖居中視圖控制器的中心,UIActivityIndicatorView必須在加載視圖的中心,但它沒有像我期待的那樣居中。
+0

你爲什麼要硬編碼任何CGRect值?大多數應該根據每個視圖的父視圖的大小來計算。 – rmaddy

回答

0

在viewDidLoad中添加此代碼它的工作原理:

[self.view addSubview: loadingView]; 
loadingView .center = CGPointMake(CGRectGetWidth(self.view.frame)/2, CGRectGetHeight(self.view.frame)/2); 
+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); 
} 
+0

這是不正確的。 'loadingView'需要以'self.view'爲中心。 'activityView'和'loadingLabel'放在'loadingView'中。 – rmaddy

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));

相關問題