Corbin의 답변을 기반으로합니다 (btw 감사합니다).
macOS 10.11 (이상) 용 자동 레이아웃이있는 Swift 3,보기 기반 NSTableView
내 설정 : NSTableCellView
자동 레이아웃을 사용하여 레이아웃이 있습니다. 여기에는 다른 요소 외에 NSTextField
최대 2 개의 행을 가질 수 있는 여러 줄 이 포함됩니다. 따라서 전체 셀보기의 높이는이 텍스트 필드의 높이에 따라 달라집니다.
두 가지 경우에 높이를 업데이트하도록 테이블 뷰를 업데이트합니다.
1) 테이블보기 크기가 조정되는 경우 :
func tableViewColumnDidResize(_ notification: Notification) {
let allIndexes = IndexSet(integersIn: 0..<tableView.numberOfRows)
tableView.noteHeightOfRows(withIndexesChanged: allIndexes)
}
2) 데이터 모델 개체가 변경되는 경우 :
tableView.noteHeightOfRows(withIndexesChanged: changedIndexes)
이렇게하면 테이블 뷰가 대리자에게 새 행 높이를 요청합니다.
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
let entity = dataChangesController.entities[row]
let cellViewIdentifier = tableCellViewIdentifier(for: entity)
var cellView: NSTableCellView!
if let savedView = savedTableCellViews[cellViewIdentifier] {
cellView = savedView
}
else if let view = tableView.make(withIdentifier: cellViewIdentifier, owner: nil) as? NSTableCellView {
savedTableCellViews[cellViewIdentifier] = view
cellView = view
}
if let entityHandler = cellView as? DataEntityHandler {
entityHandler.update(with: entity)
}
cellView.bounds.size.width = tableView.bounds.size.width
cellView.needsLayout = true
cellView.layoutSubtreeIfNeeded()
let height = cellView.fittingSize.height
return height > tableView.rowHeight ? height : tableView.rowHeight
}
먼저, 행 ( entity
)에 대한 모델 객체 와 적절한 셀 뷰 식별자를 가져와야합니다. 그런 다음이 식별자에 대한 뷰를 이미 생성했는지 확인합니다. 이를 위해 각 식별자에 대한 셀 뷰가있는 목록을 유지해야합니다.
// We need to keep one cell view (per identifier) around
fileprivate var savedTableCellViews = [String : NSTableCellView]()
저장되지 않은 경우 새 항목을 만들고 캐시해야합니다. 모델 객체로 셀 뷰를 업데이트하고 현재 테이블 뷰 너비를 기반으로 모든 것을 다시 레이아웃하도록 지시합니다. fittingSize
높이는 다음의 새로운 높이로 사용할 수 있습니다.