我见过很多类似的问题,但似乎没有什么完全是我正在寻找的。如果我错过了另一个问题中回答的解决方案,请原谅我!
对。我有一个看法。高和宽均为 160 像素。我知道该 View 将用作 subview ,并且我知道无论使用什么情况,它始终都需要以两个轴为中心。
如果以编程方式定义 View ,我如何确保它相对于其 super View 始终完全居中、水平和垂直?
到目前为止,我所拥有的只是这个简单的代码:
- (void)loadView {
self.view = [[UIView alloc] initWithFrame:CGRectMake(80, 150, 160, 160)];
self.view.backgroundColor = [UIColor greenColor];
self.view.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
[self.view release];
}
这确实实现了集中化,但仅限于最简单的情况。非常感谢任何见解。
编辑1:
添加以下代码行:
self.view.center = self.view.superview.center;
subview 的中心点成为父 View 的(0,0)坐标。也许我没有正确设置 super View ?
最佳答案
除了 @Jasarien 和 @Brad 所说的之外,不要忘记您可以使用自动调整 Spring 和支柱来强制自动居中。本质上(在 Interface Builder 中)您可以单击周围,直到没有可见的自动调整大小线,如下所示:
在代码中,您将 -[UIView autoresizingMask]
设置为:
objective-c :
(UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleBottomMargin)
Swift 3.x:
[.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
如果执行这些操作, View 将自动保持居中。
编辑#1
回答您的编辑,您不能这样做:
self.view.center = self.view.superview.center;
除非您的 View 已添加为另一个 View 的 subview ([anotherView addSubview:self.view];
)。我的猜测是 self.view.superview
返回 nil
,因此您(幸运的是)得到 {0,0}
作为尝试在 nil
上调用 center
时返回值。
将 View 居中的正确位置可能是在 View Controller 的 viewWillAppear:
方法中。一旦 View 即将出现,您就知道它必须有一个 super View (否则它会如何出现?)。您可以在那里安全地设置 View 的中心
。
关于iphone - 以编程方式使 UIView 居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2524943/