UIActivityIndi​​catorView 未居中

UIActivityIndicatorView Not Centered

我有一个带有 UIActivityIndi​​catorView 作为子视图的 TableViewController,它在内容加载时正常工作。唯一的问题是我无法将 activity 指示器置于屏幕中央。

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

尝试代码:

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

可能是因为您的视图在 xib 中的大小错误(例如,它在 xib 中为 iPhone 5 而您在 iPhone 6 中为 运行 )。 所以,你的高度和宽度计算是错误的。

改为尝试使用

CGFloat width = CGRectGetWidth(UIScreen.mainScreen.bounds);
CGFloat height = CGRectGetHeight(UIScreen.mainScreen.bounds);

希望对您有所帮助:)

尝试将此行 loadingIndicator.center = CGPointMake(width / 2, height / 2); 更改为 loadingIndicator.center = self.view.center; 并将子视图 loadingIndicator 添加到 self.view

您的代码是完美的,但我认为您在 self.view 的基础上设置了框架并在 tableview 上添加了该指示器。

所以在 self.view 上添加该指标。

如果您的问题是水平位置不正确,可能是视图的边界仍然是故事板中的自由宽度。

尝试将您的代码放在 viewDidLayoutSubviews 中。为避免重复添加到视图,将 activityObject 设置为此 class.

的 属性

当您想在屏幕上居中时,Tejvansh Singh Chhabra 的回答很好。通常,如果您想根据视图的框架或边界定位视图,请将代码放在 viewDidLayoutSubviews 阶段之后,或将 constraints 添加到视图中。

同样值得注意的是,大指示器似乎向左向上移动了 3 个像素。 (swift, iOS 9.2.1)