2
votes

Title should read: Automatically adjust width of the containing NSWindow of a view based NSTableView based on NSTableCellView's NSTextField content intrinsic content size.

A bit like this other question, I would like to implement an autocompletion NSWindow with an NSTableView inside it that adjust to the width of the length of the available autocompletions implemented as NSTextField inside an NSTableCellView. Each autocompletion should obviously be displayed on one line...

The previous question has been answered but was only related to the hight of the NSTableView. I would like to know how to do the "same" for the width. I would like to implement the solution as much as possible using auto layout.

I've tried to set the horizontal "Content Hugging Priority" and the "Content Compression Resistance Priority" to the maximum of 1000 for each view element participating in the final display of the NSWindow. I was thinking that the intrinsic content size of the NSTextField would force all other elements to adjust but it does not work.

Setting the NSTableColumn width does not work either since the NSClipView of the NSScrollView is not modified by this width: the NSScrollView adjusts and creates horizontal scroll bars to cover the entire "document".

Here is a link to a sample project to demonstrate the problem:

sample project

Any help would be greatly appreciated!

1

1 Answers

0
votes

I fixed the problem using this code with the scrollViewWidthConstraint being an IBOutlet to the NSScrollView width constraint, localTableView being an IBOutlet to the NSTableView and tableColumn being an IBOutlet to the NSTableColumn (the only one in my case).

Note: The linked project on GitHub has been updated with the changes.

override func viewDidLoad() {

    super.viewDidLoad()

    self.updateTable()
}

func updateTable() {

    localTableView.reloadData()

    var computedWidth: CGFloat = 0

    for var row = 0; row < 10; row++  {

        let tableCellView = self.tableView(localTableView, viewForTableColumn: tableColumn, row: row) as! NSTableCellView

        computedWidth = max(computedWidth, tableCellView.textField!.intrinsicContentSize.width)
    }

    scrollViewWidthConstraint!.constant = computedWidth

    scrollView.needsUpdateConstraints = true
}