2

I have a Cocoa app that shows a "quick search" window similar to Spotlight. The window contains a visual effect view and inside a NSTextField. The text field stretches across the full width of the window.

I would like to be able to move the window by dragging inside the empty area of the text field. When dragging across text in the text field, the normal editing (i.e. selection) behavior should be used instead.

In theory, moving a window by its background is easy:

window.isMovableByWindowBackground = true

However, this behavior does not work with NSTextField, because it intercepts dragging and attempts to select text instead.

Spotlight does it somehow. Here's an example:

Spotlight example

A couple of options that I considered without success:

  • Tried overriding hitTest: returning nil
  • Tried overriding mouseDown|Up|Dragging: and forwarding to superview
  • Tried to use autolayout to have text field shrink to tightly wrap around its text (could not figure this one out)
Mark
  • 6,647
  • 1
  • 45
  • 88
  • Maybe this helps: [How to resize NSTextField dynamically?](https://stackoverflow.com/questions/12705316/how-to-resize-nstextfield-dynamically). – Willeke Sep 16 '17 at 10:59

1 Answers1

4

For reference, I finally found a way:

Part 1: get NSTextField to grow/shrink with its content

Override intrinsicContentSize and measure its content:

private func measure(_ string:NSAttributedString) -> NSSize
{
    let cell = NSTextFieldCell(textCell: stringValue)
    cell.attributedStringValue = string

    return cell.cellSize
}

Part 2: view setup

  • Add a placeholder view right after the text field
  • Set up auto layout to have the placeholder view to grow and shrink

Part3: all about the details

  • Set up the placeholder view to use the iBeam cursor to make it appear like a text field
  • If the user clicks in the placeholder view, make the text field the first responder

That's it.

Mark
  • 6,647
  • 1
  • 45
  • 88