2012-11-21 46 views
1

我想創建一個寬度固定但高度可變的視圖。這意味着視圖應根據其內容高度自動調整大小,但同時應保持相同的寬度。使NSView具有固定寬度和可變高度,適合內容

我怎樣才能以編程方式實現

舉例來說,我已經得到了接下來的一段代碼來創建一個標籤和一個按鈕:

NSTextField *label = [[NSTextField alloc] initWithFrame:[self frame]]; 
[label setEditable:NO]; 
[label setBackgroundColor:[NSColor clearColor]]; 
[label setBezeled:NO]; 
[label setFont:[NSFont fontWithName:@"Lucida Grande" size:13.0]]; 
[label setStringValue:@"Sample label text"]; 

NSButton *button = [[NSButton alloc] initWithFrame:primaryBounds]; 
[button setBezelStyle:10]; 
[button setTitle:@"Sample button text"]; 
[button setBounds:NSInsetRect([button bounds], -8.0, 0)]; 
[button sizeToFit]; 

[[self contentView] addSubview:label]; 
[[self contentView] addSubview:button]; 

他們被設置爲填滿整個contentView框架。我如何設置我的label固定寬度和變量高度(基於文本內容本身)和我的button將被附加到底部的label


好吧,我已經成功地自動調整label這樣的:

NSTextView *label = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, [self frame].size.width, 0)]; 
[label setEditable:NO]; 
[label setBackgroundColor:[NSColor clearColor]]; 
[label setFont:[NSFont fontWithName:@"Lucida Grande" size:13.0]]; 
[label setString:@"Sample label text"]; 
[label setHorizontallyResizable:NO]; 
[label sizeToFit]; 

回答

1

在自動佈局用山獅,你能告訴文本字段的首選寬度應該是什麼:

[textField setPreferredMaxLayoutWidth:200] 

現在,文本字段將測量其內容的大小,就好像它在200個點處包裝一樣,並且一旦內容達到該寬度,文本字段將傾向於垂直增長。

要安裝按鈕,將標籤的底部,你會添加約束,上面寫着標籤的底部等於按鈕的頂部,再加上22:

[parentView addConstraint: 
    [NSLayoutConstraint constraintWithItem:label 
           attribute:NSLayoutAttributeBottom 
           relatedBy:NSLayoutRelationEqual 
            toItem:button 
           attribute:NSLayoutAttributeTop 
           multiplier:1 
           constant:22]]; 

或使用視覺格式的語言和標準Aqua間距:

NSDictionary *viewsDict = NSDictionaryOfVariableBindings(label, button); 
[view addConstraints: 
    [NSLayoutConstraint constraintsWithVisualFormat:@"V:[label]-[button]" 
              options:0 
              metrics:nil 
               views:viewsDict]]; 
相關問題