swift – NSTextField上的奇怪滚动

我有一个NSTextField,我尝试自动调整大小,一旦它的内容改变一定的标准.

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

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

在XCode中启动可视化调试器我发现当这种情况发生时,NSTextField:_NSKeyboardFocusClipView的私有子视图具有一个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)"
    )
  }
}

这是在NSTextFieldDelegate方法调用的:

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

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

lazy var textField: NSTextField = {
    let textField = NSTextField()
    textField.isHidden = true
    textField.isEditable = false
    textField.allowsEditingTextAttributes = true
    return textField
  }()

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

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

根据documentation

Use the NSWindow makeFirstResponder(_:) method,not this method,to
make an object the first responder. Never invoke this method directly.

此外,您是否真的需要textfield才能在水平和垂直方面发展?以高度为单位动态化显然会更加直观.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...