[英]NSLayoutConstraints code to center a view and maintain its aspect ratio
[英]Creating NSLayoutConstraints in code
這是我首次使用約束,因此請原諒基本問題。
我希望能夠設置一系列約束,以使subView小於我的視圖寬度的75%或小於我的視圖寬度的75%。 因此,如果我的subView的寬度大於視圖寬度的75%,則將其設置為完整寬度。 我要執行此操作以確保subView在iPhone和iPad上顯示良好。
使用約束是否可能? 我已經設置了兩個約束,但是如何確定約束系統是根據我的視圖的寬度來選擇的,因為我不確定這可以僅使用優先級來解決?
// Ensure it's width is either the less than 3 quarters of the page width or the full page width (including the gutter margins)
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:0.75 constant:0];
[self.constraints addObject:constraint];
constraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0];
[self.constraints addObject:constraint];
// Add the constraints to the page
[self addConstraints:self.constraints];
任何幫助都會使您深陷困境,對此深表感謝。
戴夫
有什么原因不能僅僅基於平台應用適當的約束?
NSLayoutConstraint *constraint;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
constraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:0.75 constant:0];
}
else {
constraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0];
}
[self addConstraint:constraint];
另外,根據您的評論還不清楚您是否嘗試過使用優先級...這行得通嗎?
因此,正如所討論的那樣,似乎自動布局無法在MacOS 10.8版本中處理此問題。 因此,我建議以標准代碼實現它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.