Search code examples
iosuitableviewxamarin.iosselected

Check if cell is selected and format it accordingly iOS UITableView


I am trying to implement a functionality where I want to set the first row of a UITableView as selected. The UITableView is a subview of my UIViewController . I am able to select the 1st row through my UIViewController. Like so :-

  var indexPath = NSIndexPath.FromRowSection(0, 0);

 newTableChoice.Source = new RatingScaleSource(this,data.TypeAsString ,data.Title, choiceList);
 newTableChoice.SelectRow(indexPath, false, UITableViewScrollPosition.Top);

Now I want to implement it further in my DataSource, where if the first row is selected then I want to add an accessory to it so that the user knows that particular row is selected by default.

I tried implementing this in my RatingScaleSource class which is my DataSource :-

  public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
      cell = tableView.DequeueReusableCell("ChoiceTableCell") as ChoiceTableCell;
        if (tableView.CellAt(indexPath).Selected)
        {
            cell.Accessory = UITableViewCellAccessory.Checkmark;
        }
    }

But this crashes the app as the Cell is not yet created. I want to know which Function can detect if the row is already selected and where I can add the accessory. Any help is appreciated.


Solution

  • SelectRow definition here

    We can see the following sentences in Remarks

    Calling this method does not trigger UITableViewSource.WillSelectRow(UITableView,NSIndexPath) nor will it send UITableView.SelectionDidChangeNotification notifications.

    No method will be triggered with this method.

    tableView.CellAt(indexPath) at GetCell is incorrect, because the cell hasn't returned at that time(means it is not yet created).

    I tried the following code but no luck, I think the tableview selects the row after finishing the render delegate.

    cell = tableView.DequeueReusableCell("ChoiceTableCell") as ChoiceTableCell;
    if (cell.Selected)
    {
         cell.Accessory = UITableViewCellAccessory.Checkmark;
    }
    

    Solution:

    So since you have known the index which should be selected, you can set the Accessory with same condition in GetCell

    if (indexPath.IsEqual(NSIndexPath.FromRowSection(0, 0)))
    {
        cell.Accessory = UITableViewCellAccessory.Checkmark;
    }
    else
    {
        cell.Accessory = UITableViewCellAccessory.None;
    }