【问题标题】:Vertically aligning text in an NSTextField using Swift使用 Swift 在 NSTextField 中垂直对齐文本
【发布时间】:2022-01-06 20:59:06
【问题描述】:

我一直在阅读有关如何在 NSTextField 上设置垂直对齐的各种选项。我希望文本显示在中心并在 Swift 中以编程方式进行。以下是我目前看过的内容:

我在 Swift 中尝试过的一件事是设置以下属性:

textField.usesSingleLineMode = true

任何关于将文本垂直居中的最佳方法的提示将不胜感激!

【问题讨论】:

标签: swift cocoa appkit


【解决方案1】:

这很难做到,因为 Apple 让这变得非常困难。我通过继承 NSTextFieldCell 并覆盖 drawingRectForBounds: 方法来实现它:

override func drawingRectForBounds(theRect: NSRect) -> NSRect {
    let newRect = NSRect(x: 0, y: (theRect.size.height - 22) / 2, width: theRect.size.width, height: 22)
    return super.drawingRectForBounds(newRect)
}

这只是我的方法,我确信还有更好的方法,但我还不知道。这仅适用于 TextFields 中的标准字体大小(文本高度为 22)。这就是我硬编码的原因。还没有弄清楚,如果你改变字体,如何获得单元格的高度。

结果:

【讨论】:

  • 你还能做的就是将一个不带边框的 NSTextField 作为子视图添加到 NSView 中。 :)
  • [NSLayoutManager defaultLineHeightForFont:]
  • 22 来自哪里?
  • 这是textviews的字体大小
【解决方案2】:

在操场上试试这个,它使文本完美居中,在您的项目中使用它!希望对您有所帮助!

import Cocoa

let cell = NSTableCellView()
cell.frame = NSRect(x: 0, y: 0, width: 100, height: 100)
let tf = NSTextField()
tf.frame = cell.frame
tf.stringValue = "MyTextfield"
tf.alignment = .Center

let stringHeight: CGFloat = tf.attributedStringValue.size().height
let frame = tf.frame
var titleRect:  NSRect = tf.cell!.titleRectForBounds(frame)

titleRect.size.height = stringHeight + ( stringHeight - (tf.font!.ascender + tf.font!.descender ) )
titleRect.origin.y = frame.size.height / 2  - tf.lastBaselineOffsetFromBottom - tf.font!.xHeight / 2
tf.frame = titleRect
cell.addSubview(tf)

【讨论】:

    【解决方案3】:

    我在 NSView 中添加了 NSTextField 并将其居中。

    另一个解决方案是(在 iOS 项目中)创建一个 UILabel 并允许它调整其大小 (sizeToFit()) 并再次将其嵌入到 UIView 中。

    我个人不喜欢之前答案中的计算,iOS 的第二个解决方案适用于所有文本大小和行号。

    【讨论】:

      【解决方案4】:

      我还面临 NSTextField 的垂直对齐问题。我的要求涉及在 NSTextField 中呈现单行字符串。此外, 需要调整文本字段的大小,这意味着我们已经在调整大小时以编程方式调整了文本字段内文本的字体点大小。在这种情况下,我们面临垂直对齐问题 - 对齐错误很难以直接的方式掌握/理解。

      终于奏效了:

      所以,在我的场景中,一个简单的, 在界面生成器中关闭“单行模式”
      文本字段解决了这个问题。

      【讨论】:

      • 这对我也有用。所建议的子类化方法都不是很正确——文本有时会被剪掉。
      【解决方案5】:

      接受的答案完美无缺,这是 Swift3 版本。

      class VerticallyAlignedTextFieldCell: NSTextFieldCell {
          override func drawingRect(forBounds rect: NSRect) -> NSRect {
              let newRect = NSRect(x: 0, y: (rect.size.height - 22) / 2, width: rect.size.width, height: 22)
              return super.drawingRect(forBounds: newRect)
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-04-29
        • 2012-01-27
        • 2013-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多