【问题标题】:Programmatically make a multi-line label以编程方式制作多行标签
【发布时间】:2012-02-22 15:39:28
【问题描述】:

我需要以编程方式制作一些标签和文本字段。我可以到达那里。

    //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];

但我在文档中找不到任何可以让我设置 wrap 属性的内容。在 IB 中,该属性是带有“滚动、换行和截断”选项的布局。 NSTextField 没有设置它的方法,如果我沿着继承链上升,NSControl 也没有。 NSView 有一个 setNeedsLayout 方法,但似乎不相关:

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 也没有任何方法。任何帮助,将不胜感激。

【问题讨论】:

    标签: cocoa nstextfield


    【解决方案1】:

    在 OS X 10.11 和 Swift 2.1 中,以下内容帮助了我:

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

    如果使用 AutoLayout,则需要设置压缩阻力。

    【讨论】:

      【解决方案2】:

      这对我有用:

      textField.usesSingleLineMode = false
      textField.cell?.wraps = true
      textField.cell?.scrollable = false
      

      【讨论】:

      • 最佳答案!
      【解决方案3】:

      未经测试,但NSTextFieldCellsetWraps:(继承自NSCell)应该可以满足您的需求。

      要获取单元格,请将cell 方法发送到文本字段。 NSTextFieldNSControl继承了cell方法,所以如果你想阅读文档,你需要在文档中搜索NSControl

      详细了解 NSCell docs 中的单元格如何工作。

      【讨论】:

      • 谢谢,但是开发人员页面上没有 setWraps 方法,并且在我构建时会引发警告:developer.apple.com/library/mac/#documentation/Cocoa/Reference/… 它看起来也像 NSTextField 默认情况下会根据您最初的宽度和高度进行换行提供它。
      • 所以我必须引用 NSTextFieldCell 本身吗?如果是这样,我该怎么做?
      猜你喜欢
      • 2022-01-24
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多