Search code examples
xamarinxamarin.mac

How can I get the row and column of an edited cell from NSTableView using Xamarin.Mac?


I am building a Xamarin.Mac application, and one of the ViewControllers contains an NSTableView. I have successfully been able to populate the table view, but I would like the user to be able to edit some of the cell contents.

Functionally, I am also able to get the cell editable. However, I cannot extract the row and the column for the edited cell. Is this possible?

I have the NSTableViewDelegate code:

public override NSView GetViewForItem(NSTableView tableView, NSTableColumn tableColumn, nint row)
{
    // Get the data
    var Data = this._dataSource.DataRecords[(int)row];

    NSTextField view = (NSTextField)tableView.MakeView(CellIdentifier, this);
    if (view == null)
    {
        view = new NSTextField();
        view.Identifier = CellIdentifier;
        view.BackgroundColor = NSColor.Clear;
        view.Bordered = false;
        view.Selectable = true;
        view.Editable = true;
        view.EditingEnded += this.EditingEnded;
    }

    // Setup view based on the column selected
    if(tableColumn.Title.Equals(string.Empty)) {
        view.IntValue = Convert.ToInt16(row);
    }
    else {
        view.StringValue = Data.Get(tableColumn.Title).ToString();
    }

    return view;
}

void EditingEnded(object sender, EventArgs e)
{
    // I can get a reference to the correct, edited, NSTextField 
    //   with the following line.
    var textField = ((NSNotification)sender).Object as NSTextField;

    // However, HERE, I would like to know what row and column was edited so 
    //  that I can update my source data with the user-made change.
}

Does anyone know how to use this logic to get the edited cell's position in the NSTableView?

I am using Xamarin.Mac, but I assume the same logic/question would apply if I was using Swift or Objective-C for my app. I'd happily take an answer in either of those languages as well.


Solution

  • You can get the column and row for any NSView in your NSTableView by using the NSTableView's:

    • RowForView
    • ColumnForView

    Example:

    var textField = ((NSNotification)sender).Object as NSTextField;
    var row = someTableView.RowForView(textField);
    var column = someTableView.ColumnForView(textField);