What’s the need of NSGridView :
Suppose you want to create a view which should look like this and to create it we have following available options:
1. Autolayout :
- Maintanence on constraints is complicated
2. NS/UIStackView :
- Arranging a sequence of items
- Fine control over content size and spacing
To make the above design less complicated and easily designable Apple has introduced a 3rd option.
3. NSGridView :
- Places views in an explicitly defined grid
- Content aligned across rows and columns
- Great for arranging static grid-like UI
NSGridView consists of
1. NSGridRow and NSGridColumn : It has following attributes
- Automatic or explicit sizing
- Optional padding and spacing
- Hidden rows and columns
2. NSGridCell : It has following attributes
- Each cell manages a content view
- Adjustable placement
Start Designing with NSGridView :
For now this view is not available in Interface Builder you have to create it via programming only.
let empty = NSGridCell.emptyContentView let gridView = NSGridView(views: [ [brailleTranslationLabel, brailleTranslationPopup], [empty, showContractedCheckbox], [empty, showEightDotCheckbox], [statusCellsLabel, showGeneralDisplayCB], [empty, textStyleCB], [showAlertCB] ])
This code has only added subview to NSGridView but alignment (spacing and padding) is not proper.
Now set the hugging priority and remove spaces between rows and columns.
gridView.setContentHuggingPriority(600, for: .horizontal) gridView.setContentHuggingPriority(600, for: .vertical)
Now set the placement of first colmn.
// the first column needs to be right-justified: gridView.column(at: 0).xPlacement = .trailing // all cells use firstBaseline alignment gridView.rowAlignment = .firstBaseline
Now set the verticle padding as per design.
// We need a little extra vertical space around the popup: let row = gridView.cell(for: brailleTranslationPopup)!.row! row.topPadding = 5 row.bottomPadding = 5 gridView.cell(for:statusCellsLabel)!.row!.topPadding = 6
Now we need alert message checkbox to be centered.
// Special treatment for centered checkbox: let cell = gridView.cell(for: showAlertCB)! cell.row!.topPadding = 4 cell.row!.mergeCells(in: NSMakeRange(0, 2)) cell.xPlacement = .none let centering = showAlertCB.centerXAnchor.constraint(equalTo: textStyleCB.leadingAnchor) cell.customPlacementConstraints = [centering]
Congratulations! You are done with NSGridView.