Created
March 16, 2020 17:22
-
-
Save pilky/ad221d7e4a8bec93da11bd2e24c71cf7 to your computer and use it in GitHub Desktop.
Dynamic NSOutlineView row heights
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyOutlineDelegate: NSObject, NSOutlineViewDelegate { | |
//The cell we'll use for calculating sizes, should be the same cell used in the outline | |
lazy var sizingCell: MyCell = { | |
let cell = MyCell(frame: .zero) | |
cell.translatesAutoresizingMaskIntoConstraints = false | |
return cell | |
}() | |
lazy var sizingCellWidthAnchor: NSLayoutConstraint = { | |
return self.sizingCell.widthAnchor.constraint(equalToConstant: 1000) | |
}() | |
func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat { | |
//Set the cell's object value to the item (or whatever property you use to set the data) | |
self.sizingCell.objectValue = item | |
//Just to make sure the width anchor is enabled, you could do this in a viewDidLoad() method rather than here | |
self.sizingCellWidthAnchor.isActive = true | |
//You will need to calculate the width you want for the item based on indentation (for a table view this would be constant but for an outline I think you need to calculate per item) | |
let width = … | |
//We set the width (unfortunately AppKit doesn't have an equivalent to UIView.systemLayoutSizeFitting(_: CGSize) | |
self.sizingCellWidthAnchor.constant = width | |
//Force a layout (can't remember if this is needed or if fittingSize calls it for us, but I put it in for completeness) | |
self.sizingCell.layoutIfNeeded() | |
//Get the fitting size height for the cell height | |
return self.sizingCell.fittingSize.height | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment