I have a table view where each row has two labels, one left-aligned and one right-aligned. I would like to reload a single row, but doing so causes the right-aligned label to hug the left-aligned label.
Before the reload:
After the reload:
Reloading the whole table view instead, or disabling automatic row height, solves the issue. Can a single row be reloaded without resorting to these two workaround?
class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
override func loadView() {
let tableView = NSTableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.dataSource = self
tableView.delegate = self
tableView.usesAutomaticRowHeights = true
let column = NSTableColumn()
column.width = 400
tableView.addTableColumn(column)
let scrollView = NSScrollView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.documentView = tableView
view = scrollView
Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { _ in
print("reload")
tableView.reloadData(forRowIndexes: IndexSet(integer: 2), columnIndexes: IndexSet(integer: 0))
// tableView.reloadData()
}
}
func numberOfRows(in tableView: NSTableView) -> Int {
return 5
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = NSTableCellView()
let textField1 = NSTextField(labelWithString: "hello")
textField1.translatesAutoresizingMaskIntoConstraints = false
let textField2 = NSTextField(wrappingLabelWithString: "world")
textField2.translatesAutoresizingMaskIntoConstraints = false
textField2.alignment = .right
let stack = NSStackView(views: [
textField1,
textField2
])
stack.translatesAutoresizingMaskIntoConstraints = false
stack.distribution = .fill
cell.addSubview(stack)
NSLayoutConstraint.activate([stack.topAnchor.constraint(equalTo: cell.topAnchor, constant: 0), stack.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 0), stack.bottomAnchor.constraint(equalTo: cell.bottomAnchor, constant: 0), stack.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: 0)])
return cell
}
}