Я хотел бы опубликовать свое решение, обновленное для Swift 4, используя привязки Какао и фактический флаг isHidden
, не затрагивая ширину столбцов (так как вам может потребоваться восстановить исходное значение впоследствии ...). Предположим, у нас есть флажок для переключения видимости некоторых столбцов (или вы всегда можете переключить переменную hideColumnsFlag
в приведенном ниже примере любым другим способом, который вам нравится):
class ViewController: NSViewController {
// define the boolean binding variable to hide the columns and use its name as keypath
@objc dynamic var hideColumnsFlag = true
// Referring the column(s)
// Method 1: creating IBOutlet(s) for the column(s): just ctrl-drag each column here to add it
@IBOutlet weak var hideableTableColumn: NSTableColumn!
// add as many column outlets as you need...
// or, if you prefer working with columns' string keypaths
// Method 2: use just the table view IBOutlet and its column identifiers (you **must** anyway set the latter identifiers manually via IB for each column)
@IBOutlet weak var theTableView: NSTableView! // this line could be actually removed if using the first method on this example, but in a real case, you will probably need it anyway.
// MARK: View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Method 1
// referring the columns by using the outlets as such:
hideableTableColumn.bind(.hidden, to: self, withKeyPath: "hideColumnsFlag", options: nil)
// repeat for each column outlet.
// Method 2
// or if you need/prefer to use the column identifiers strings then:
// theTableView.tableColumn(withIdentifier: .init("columnName"))?.bind(.hidden, to: self, withKeyPath: "hideColumnsFlag", options: nil)
// repeat for each column identifier you have set.
// obviously use just one method by commenting/uncommenting one or the other.
}
// MARK: Actions
// this is the checkBox action method, just toggling the boolean variable bound to the columns in the viewDidLoad method.
@IBAction func hideColumnsCheckboxAction(_ sender: NSButton) {
hideColumnsFlag = sender.state == .on
}
}
Как вы, возможно, заметили, пока нет способа привязать флаг Hidden
в Интерфейсном Разработчике, как на XCode10: вы можете видеть привязки Enabled
или Editable
, но только программно вы будете иметь доступ к isHidden
флаг для столбца, как он называется в Swift.
Как отмечалось в комментариях, второй метод основан на идентификаторах столбцов, которые необходимо вручную установить либо через Интерфейсный Разработчик в поле Identity после выбора соответствующих столбцов, либо, если у вас есть массив имен столбцов, вы можете перечислять столбцы таблицы. и назначьте идентификаторы, а также привязки вместо повторения похожих строк кода.