Programmatically setting an NSTextField frame size in an NSTableCellView

224 Views Asked by At

I use storyboard to design my view-based NSTableView and its subviews with auto layouts. It is working fine and behaves as expected.

In my NSTableCellView, I have multiples NSTextField. I wish to programmatically change the frame in one of them. So I tried something like this.

dataSource = NSTableViewDiffableDataSource<Section, Item>(tableView: someTableView, cellProvider: { tableView, tableColumn, row, item -> NSView in
            guard let tableCellView = tableView.makeView(withIdentifier: .someTableCellView, owner: self) as? SomeTableCellView else {
                fatalError()
            }

            tableCellView.randomTextField.stringValue = "Something..."
            tableCellView.someTextField.stringValue = "Blah..."

            //...

            let size = NSSize(width: 200, height: 50)
            tableCellView.someTextField.setFrameSize(size)
            tableCellView.someTextField.needsLayout = true
            tableCellView.needsLayout = true

            return tableCellView
        })

For tableCellView.someTextField and tableCellView, I tried the following combination and nothing seems to change:

  • .needsDisplay = true
  • .needsLayout = true
  • .invalidateIntrinsicContentSize()
  • .layoutSubtreeIfNeeded()
  • .updateConstraints()
  • .layout()

Why is it so hard? My understanding is that if I set a new frame size for someTextField and then inform tableCellView that it needs to recalculate the subviews layout positions because someTextField has been modified so other subviews needs to reposition themselves to be consistent with auto layout constraints.

0

There are 0 best solutions below