簡體   English   中英

中心視圖在另一個視圖內

[英]Center view inside another view

我有一個稱為配置文件的視圖,該視圖在情節(0,0,320,60)占據了(0,0,320,60)大小,該視圖占據了全角但高度為60,並且我試圖將另一個名為“排名”的視圖放置在中間,以及該設備是什么iPhone4s ,5s,6s,6應該只接受我的看法並將其放在中心。

這是我嘗試過的:

ranking.frame = CGRectMake(0, 0, 120, 60);
ranking.center = self.Profile.center;

當前代碼未在所有設備中集中顯示我的視圖。 我該怎么做才能動態地做到這一點?

您可以通過以下方法使用自動版式:

+ (void)centerView:(UIView *)view inContainerView:(UIView *)containerView withSuperView:(UIView *)superView
{
    [superView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
    [superView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];
}

您可以在ViewController或助手類中添加上述方法。 在視圖上使用“自動布局”之前,請記住將“ translatesAutoresizingMaskIntoConstraints屬性設置為“ false”。

因此,如果ranking是您的子視圖,而self.Profile是您的超級視圖,則可以執行以下操作。

UIView *ranking = [[UIView alloc] init];
ranking.translatesAutoresizingMaskIntoConstraints = false;
[self.Profile addSubview:ranking];
[[self class] centerView:ranking inContainerView:self.Profile withSuperView:self.Profile];
[self.Profile addConstraint:[NSLayoutConstraint constraintWithItem:ranking attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:120]];
[self.Profile addConstraint:[NSLayoutConstraint constraintWithItem:ranking attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:60]];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM