2013-05-13 68 views
0

實施以下遇到問題:NSView Contraints - 如何強制子視圖的縱橫比保持不變?

+-------------------+ 
|     | 
|     | 
|  RESIZABLE  | 
|     | 
|  NSVIEW  | 
|     | 
|     | 
|     | 
|     | 
|     | 
|     | 
|     | 
|     | 
|     | 
|+-----------------+| 
||     || 
||  STATIC  || 
||     || 
||  SUBVIEW  || 
||     || 
|+-----------------+| 
+-------------------+ 

當子視圖的縱橫比必須保持恆定(如用戶改變可調整大小的視圖的寬度)。

我想使用約束做,到目前爲止,我已經有了:

//This is a snippet of the resizable view class 

[self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:subview attribute:NSLayoutAttributeWidth multiplier:1 constant:0]]; 
[self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:subview attribute:NSLayoutAttributeBottom multiplier:1 constant:0]]; 

//This is a snippet of the subview class 

[self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:aspectRatio constant:0]]; 

可調整大小的視圖的框架初始設置。在這種情況下,不設置子視圖的框架是有意義的?目前,主視圖似乎消失了 - 它的寬度開始爲零。

我應該如何解決這個問題 - 如果可能的話,我喜歡使用約束!

+0

我會認爲你展示的前兩個約束是背對背的;你不想讓子視圖受到父視圖(可調整大小)的限制嗎? – trojanfoe 2013-05-13 11:54:54

+0

@trojanfoe這就是我一開始想到的,但是這樣做會產生一個錯誤:「無法在視圖上安裝約束,約束是否從視圖的子樹外引用某個東西?這是非法的。」 – 2013-05-13 11:56:47

+0

嗯,我不是專家,但我知道你可以表達約束WRT的超視圖,但你可能需要使用該方法的視覺語言版本。 – trojanfoe 2013-05-13 11:58:11

回答

3

這可以通過在IB中設置大部分約束,然後在代碼中更改其中的一個來完成。靜態子視圖應該有任何想要調整大小的視圖的邊和底部的間距約束,以及固定的高度約束 - 在創建這些約束之後,如果有一個約束,您應該可以將約束刪除到可調整大小的視圖頂部。做一個IBOutlet的高度約束,並改變在這樣的代碼(heightCon是我的出路,而這個代碼是在靜態子視圖子類):

- (void)awakeFromNib { 
    [self removeConstraint:self.heightCon]; 
    self.heightCon = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:.54 constant:0]; 
    [self addConstraint:self.heightCon]; 
} 

的0.54數量從我的高度的初始比例來到IB的寬度。

+0

是的,除了這可能應該在視圖控制器的'-viewDidLoad'而不是應用程序委託。 – paulmelnikow 2013-05-13 16:06:03

+0

@noa,在OS X中沒有viewDidLoad。 – rdelmar 2013-05-13 16:07:23

+0

在OS X的nib所有者的'-awakeFromNib'中。我通常設置一個標誌以避免多次運行我的設置代碼,因爲在某些情況下,該方法被稱爲多於一旦。對於NSWindowController,你也可以使用'-windowControllerDidLoadNib'。 – paulmelnikow 2013-05-13 16:12:16