Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically make a multi-line label

I need to programmatically make some labels and text fields. I can get there.

    //create the file name label
    NSTextField* newFileNameLabel = [[NSTextField alloc] initWithFrame:NSMakeRect(objXPos, objYPos, 300.0, 20.0)];
    //set properties
    [newFileNameLabel setBordered: NO];
    [newFileNameLabel setTextColor: [NSColor whiteColor]];
    [newFileNameLabel setDrawsBackground:NO];
    [newFileNameLabel setEditable:NO];
    [newFileNameLabel setStringValue: @"File Name:"];

    [vSheetView addSubview:newFileNameLabel];

But I couldn't find anything in the docs that would let me set a wrap property. In IB the property is layout with 'scroll, wrap and truncate' as its options. NSTextField doesn't have a method to set this, and if I go up the inheritance chain neither does NSControl. NSView has a setNeedsLayout method but it doesn't seem related:

You only ever need to invoke this method if your view implements custom layout 
not expressible in the constraint-based layout system by overriding the layout method. 
The system invokes this method automatically for all views using constraints for layout.

NSTextFieldCell doesn't have any methods either. Any help would be appreciated.

like image 435
PruitIgoe Avatar asked Feb 22 '12 15:02

PruitIgoe


1 Answers

In OS X 10.11 and Swift 2.1 the following helped me:

multilineLabel.lineBreakMode = .ByWordWrapping
multilineLabel.setContentCompressionResistancePriority(250, forOrientation: .Horizontal)

Setting the compression resistance is required if you use AutoLayout.

like image 177
Vladislav Savchuk Avatar answered Oct 19 '22 23:10

Vladislav Savchuk