我想创建一个宽度固定但高度可变的视图。这意味着视图应根据其内容高度自动调整大小,但同时应保持相同的宽度。
我怎样才能以编程方式实现这一目标?
例如,我有下一段代码来创建标签和按钮:
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
框架。如何设置 mylabel
具有固定宽度和可变高度(基于自身的文本内容),并将 mybutton
附加到底部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];