Programmatically make a multi-line label

人走茶凉 提交于 2020-07-03 06:16:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!