-1

I have a NSTextfield in a TableView. The content mode is configured to ViewBased. So I have the type: NSTableCellView.

Example of my Table View:

enter image description here

My problem is that I can't edit until I have selected the line. However, I want to click on the text field independently of the line and edit directly without selecting the whole line.

Current solution: In the Table View I can currently set the highlight to None and then direct editing works, but I still want to be able to select the whole row when I click outside the Textfield in the row.

I would be very happy if someone could help me. Thanks a lot!

Fatih
  • 3
  • 2

1 Answers1

1

Disclaimer - this is adapted after the nice answer from here.

One possible approach is to subclass NSTableView and override hitTest in order to send the user interaction events directly to the text field instead of the cell view:

override func hitTest(_ point: NSPoint) -> NSView? {
    let myPoint = superview!.convert(point, to: self)
    let column = self.column(at: myPoint)
    let row = self.row(at: myPoint)

    // if we find an editable text field at this point, we return it instead of the cell
    // this will prevent any cell reaction
    if row >= 0, column >= 0,
        let cell = view(atColumn: column, row: row, makeIfNecessary: false),
        let textField = cell.hitTest(convert(myPoint, to: cell.superview)) as? NSTextField,
        textField.isEditable {
        return textField
    } else {
        return super.hitTest(point)
    }
}
Cristik
  • 30,989
  • 25
  • 91
  • 127
  • Thanks a lot, you solved my problem! But now I have the problem that the clickable area of the textfield is further down than the visible area. – Fatih Dec 28 '19 at 23:35
  • The `point` argument of `hitTest` is in the coordinate system of the view’s superview, not of the view itself. `column(at:)` and `row(at:)` expect a point in the coordinate system of the table view. – Willeke Dec 28 '19 at 23:40
  • Yeah, exactly @Willeke you're right. Actually the convert function should solve the problem, but it doesn't work properly. So you have to click with the mouse a little bit further down, then it works. If I only use point, then I only get the first entry in the textfield. With the second entry it doesn't work at all. I think, if you modify the convert function or give an alternative, it should work fine. – Fatih Dec 29 '19 at 00:40
  • @Willeke right, don't know how I missed that, thanks, updated the answer. – Cristik Dec 29 '19 at 06:38
  • @Fatih updated the answer per Willeke's comment, run some tests with two textfield's per cell and the fields get selected as expected. – Cristik Dec 29 '19 at 06:40