为什么我的UIActivityIndicatorView没有居中显示在屏幕上?

3
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        activityIndicator.center = CGPointMake(self.view.bounds.size.width / 2.0f, self.view.bounds.size.height / 2.0f);

目前它出现在底部的下半部分。

你是将它直接添加到 self.view 还是其子视图中的一个? - Jonathan Grynspan
[self.view addSubview:activityIndicator]; 将activityIndicator添加到self.view中。 - Strong Like Bull
根据您的一些评论,似乎您的视图比您想象的要高。这可能是因为您在IB中设计iPhone 5屏幕时,在较小的屏幕设备上运行造成的。 - tybro0103
6个回答

15

这将把指示器放在您的视图中心(而非屏幕中心):

activityIndicator.center = CGPointMake(self.view.bounds.size.width / 2.0f, self.view.bounds.size.height / 2.0f);
activityIndicator.autoresizingMask = (UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin)

当尺寸发生变化(例如屏幕方向切换)时,自动调整大小会将其保持在中心。

如果它不起作用,那么你的问题可能出现在其他地方。尝试记录视图的大小,也许它的位置不正确?

NSLog(@"View frame: %@", NSStringFromCGRect(self.view.frame));

2
为什么不试试这种方式?
activityIndicator.center =  self.view.center;

activityIndicator.autoresizingMask = (UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin)

这个功能很好地工作,不需要像其他人提到的那样进行计算。


2
您可以这样做:
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicator.frame = CGRectMake(self.view.bounds.size.width / 2.0f - activityIndicator.frame.size.width /2.0f, self.view.bounds.size.height / 2.0f - activityIndicator.frame.size.height /2.0f, activityIndicator.frame.size.width, activityIndicator.frame.size.height);
//then add to the view

1
它出现在同一位置。大约在屏幕的三分之四下方。 - Strong Like Bull

1
如果您正在根据以下逻辑将指示器添加到parentView,则应该将指示器居中于父级 - 这对我很有效。
 // ...
 CGSize parentSize = parentView.frame.size;
 UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
 activityIndicator.center = CGPointMake(parentSize.width/2, parentSize.height/2);
 // ...

0

在viewDidLayoutSubviews中设置居中。

- (void)viewDidLayoutSubviews {
self.myActivityIndicator.center = self.view.center; }

谢谢 :)


-3

我也遇到了这个问题,试试这个方法

activityIndicator.center =CGPointMake(480/2.0, 320/2.0);

1
只有当视图始终为480x320时,才能正常工作。如果应用程序在iPhone 5上运行或处于不同的方向,会发生什么? - tybro0103
它只适用于静态屏幕尺寸,例如 iPhone 3.5 英寸。 - Girish

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