Is it possible to create a view-based NSTableView purely in code?

后端 未结 2 998
闹比i
闹比i 2020-12-10 02:19

I have successfully created a cell-based NSTableView purely in code. I would like to make the cells a little more interesting and I have read that I need to create a view-ba

2条回答
  •  旧时难觅i
    2020-12-10 03:09

    This was quite useful in my attempt to program scrolling tables without IB & Nibs. Here's my toy version, updated to Swift 4.2.

    The custom cell view subclass is only there to let me see that cells actually get re-used, which they do:

        import Cocoa
    
        class DIYTableViewDataSource: NSObject, NSTableViewDataSource {
    
            func numberOfRows(in tableView: NSTableView) -> Int {
                return 25
            }
        }
    
        class CustomTableCellView: NSTableCellView {
            var count = 1
        }
    
        func createCell(_ id: NSUserInterfaceItemIdentifier) -> CustomTableCellView {
            // Create a text field for the cell
            let textField = NSTextField()
            textField.backgroundColor = NSColor.clear
            textField.translatesAutoresizingMaskIntoConstraints = false
            textField.isBordered = false
    
            // Create a cell
            let cell = CustomTableCellView() // Doing this to see that cells get re-used
            cell.identifier = id
            cell.addSubview(textField)
            cell.textField = textField
    
            // Constrain the text field within the cell
            textField.widthAnchor.constraint(equalTo: cell.widthAnchor).isActive = true
            textField.heightAnchor.constraint(equalTo: cell.heightAnchor).isActive = true
    
            textField.bind(NSBindingName.value, to: cell, withKeyPath: "objectValue", options: nil)
    
            return cell
        }
    
        class DIYTableViewDelegate: NSObject, NSTableViewDelegate {
    
             func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
                 let id = tableColumn!.identifier
                 var view = tableView.makeView(withIdentifier: id, owner: nil) as? CustomTableCellView
                 if view == nil {
                     view = createCell(id)
                 }
                 view!.textField!.stringValue = "\(id.rawValue) \(row) \(view!.count)"
                 view!.count += 1
    
                 return view
             }
         }
    

提交回复
热议问题