[英]Trying to center a view within its superview
我在UIView
上創建了一個類別,以方便地以編程方式定位和調整視圖大小。 我想創建一個方法,將給定視圖在其superview
視圖中水平或垂直居中。 因此,我可以執行以下操作:
類別
- (void)centerHorizontally {
self.center = CGPointMake(self.window.superview.center.x, self.center.y);
}
- (void)centerVertically {
self.center = CGPointMake(self.center.x, self.window.superview.center.y);
}
采用
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[v centerHorizontally];
但是,這似乎不起作用。 我的解決方案有何不正確之處?
您需要先將視圖添加到父視圖,然后才能將其居中。
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[someOtherView addSubview:v];
[v centerHorizontally];
您的類別不正確。 不要牽扯到窗戶。 您需要基於超級視圖的大小:
- (void)centerHorizontally {
self.center = CGPointMake(self.superview.bounds.size.width / 2.0, self.center.y);
// or
self.center = CGPointMake(CGRectGetMidX(self.superview.bounds), self.center.y);
}
- (void)centerVertically {
self.center = CGPointMake(self.center.x, self.superview.bounds.size.height / 2.0);
// or
self.center = CGPointMake(self.center.x, CGRectGetMidY(self.superview.bounds));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.