问题
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.
回答1:
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.
回答2:
This works for me:
textField.usesSingleLineMode = false
textField.cell?.wraps = true
textField.cell?.scrollable = false
回答3:
Not tested, but setWraps:
of NSTextFieldCell
(inherited from NSCell
) should do what you are after.
To get the cell, send the cell
method to the text field. NSTextField
inherits the cell
method from NSControl
, so if you want to read the docs, you need to search the docs for NSControl
.
More about how cells work in the NSCell docs.
来源:https://stackoverflow.com/questions/9397940/programmatically-make-a-multi-line-label