NSTextField上的奇怪滚动

fes*_*ast 11 cocoa nstextfield appkit swift

我有一个NSTextField我尝试在它的内容发生变化时根据某个标准自动调整大小.

有时,当开始输入内容时,开始向上(或向下)移动文本字段的可见部分,如下面的gif所示:

GIF

如果我在里面点击NSTextField,内容会再次出现在正确的位置.

发射了XCode中的可视化调试器,我看到的是,当这种情况发生,私人子视图NSTextField:_NSKeyboardFocusClipView拥有frame它的Y坐标有一个负数.

我不确定是什么原因引起的.

这是我的textField调整大小行为:

import Cocoa

struct TextFieldResizingBehavior {
  let maxHeight: CGFloat = 100000.0
  let maxWidthPadding: CGFloat = 10
  let minWidth: CGFloat = 50
  let maxWidth: CGFloat = 250

  func resize(_ textField: NSTextField) {
    let originalFrame = textField.frame

    var textMaxWidth = textField.attributedStringValue.size().width
    textMaxWidth = textMaxWidth > maxWidth ? maxWidth : textMaxWidth
    textMaxWidth += maxWidthPadding

    var constraintBounds: NSRect = textField.frame
    constraintBounds.size.width = textMaxWidth
    constraintBounds.size.height = maxHeight

    var naturalSize = textField.cell!.cellSize(forBounds: constraintBounds)

    // ensure minimun size of text field
    naturalSize.width = naturalSize.width < minWidth ? minWidth : naturalSize.width

    if originalFrame.height != naturalSize.height {
      // correct the origin in order the textField to grow down.
      let yOffset: CGFloat = naturalSize.height - originalFrame.height
      let newOrigin = NSPoint(
        x: originalFrame.origin.x,
        y: originalFrame.origin.y - yOffset
      )
      textField.setFrameOrigin(newOrigin)
    }

    textField.setFrameSize(naturalSize)

    Swift.print(
      "\n\n>>>>>> text field resized " +
        "\nnaturalSize=\(naturalSize)" +
        "\noriginalFrame=\(originalFrame)-\(originalFrame.center)" +
        "\nnewFrame=\(textField.frame)-\(textField.frame.center)"
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

NSTextFieldDelegate方法上调用:

extension CanvasViewController: NSTextFieldDelegate {
  override func controlTextDidChange(_ obj: Notification) {
    if let textField = obj.object as? NSTextField {
      textFieldResizingBehavior.resize(textField)
    }
  }
Run Code Online (Sandbox Code Playgroud)

最后我的textfield在viewController中声明如下:

lazy var textField: NSTextField = {
    let textField = NSTextField()
    textField.isHidden = true
    textField.isEditable = false
    textField.allowsEditingTextAttributes = true
    return textField
  }()
Run Code Online (Sandbox Code Playgroud)

完整代码:https://github.com/fespinoza/linked-ideas-osx

lax*_*089 1

问题的一部分是您直接调用该becomeFirstResponder方法。你不应该这样做。

根据文档

使用 NSWindow makeFirstResponder(_:) 方法(而不是此方法)使对象成为第一响应者。切勿直接调用此方法。

此外,您真的需要文本字段能够水平和垂直增长吗?仅根据高度使其动态显然会更加直接。