我有一个带有UIActivityIndicatorView的TableViewController作为子视图,而内容加载并且它的工作方式应该如此。唯一的问题是我无法将活动指示器置于屏幕中心。
CGFloat width = CGRectGetWidth(self.view.bounds);
CGFloat height = CGRectGetHeight(self.view.bounds);
loadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(width / 2, height / 2, 125, 125)];
loadingIndicator.center = CGPointMake(width / 2, height / 2);
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
loadingIndicator.hidesWhenStopped = YES;
[self.tableView addSubview:loadingIndicator];
[loadingIndicator startAnimating];
也许是因为你的视图在xib中的大小不合适(例如,它在xib中用于iPhone 5,而你在iPhone 6上运行它)。所以,你的身高和宽度计算是错误的。
相反,尝试使用
CGFloat width = CGRectGetWidth(UIScreen.mainScreen.bounds);
CGFloat height = CGRectGetHeight(UIScreen.mainScreen.bounds);
希望能帮助到你 :)
试试代码:
CGFloat width = CGRectGetWidth(self.tableView.bounds);
CGFloat height = CGRectGetHeight(self.tableView.bounds);
UIActivityIndicatorView *loadingIndicator;
loadingIndicator = [[UIActivityIndicatorView alloc]init];
loadingIndicator.center = CGPointMake(width / 2, height / 2);
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
loadingIndicator.hidesWhenStopped = YES;
[self.tableView addSubview:loadingIndicator];
[loadingIndicator startAnimating];
尝试
[loadingIndicator setCenter:[self.tableView center]];
尝试将此行loadingIndicator.center = CGPointMake(width / 2, height / 2);
更改为loadingIndicator.center = self.view.center;
并将subviewloadingIndicator
添加到self.view
你的代码是完美的,但我认为你在self.view的基础上设置了框架,并在tableview上添加了该指标。
所以在self.view上添加该指标。
如果你的问题是水平位置不正确,那么视图的界限可能仍然是故事板的自由宽度。
尝试将您的代码放在viewDidLayoutSubviews中。要避免重复添加到视图,请将activityObject设置为此类的属性。
当你想要在屏幕中居中时,Tejvansh Singh Chhabra的答案很好。通常,如果您想基于视图的框架或边界定位视图,请在viewDidLayoutSubviews阶段之后放置代码,或者向视图添加约束。