Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin.iOS UITableView, how do you force a cell to update?

I am using Xamarin.iOS and cannot figure out how to update a single cell. In WPF ListView, I can just do a binding and have the cell's properties do an inotifypropertychanged and it automatically happens through the binding. Is there some equivalent functionality in Xamarin.iOS? It seems super cumbersome to update UITableView cells without just wiping them out and re-adding them..

What is the best way to update individual cells?

like image 480
Curtis Avatar asked Aug 23 '13 16:08

Curtis


2 Answers

Assuming your UITableView is stored in a "tableView" variable:

NSIndexPath[] rowsToReload = new NSIndexPath[] {
    NSIndexPath.FromRowSection(1, 0) // points to second row in the first section of the model
};
tableView.ReloadRows(rowsToReload, UITableViewCellRowAnimation.None);
like image 83
Dimitris Tavlikos Avatar answered Oct 22 '22 05:10

Dimitris Tavlikos


Create a subclass of UICell and bind to INotifyPropertyChanged there.

You can create a public property for the model object that the UICell is displaying.

Then update the cell's display properties when the model changes, or when a property changes...

public class CarCell : UITableViewCell
{
    private Car car;

    public Car Car
    {
        get { return this.car; }
        set
        {
            if (this.car == value)
            {
                return;
            }

            if (this.car != null)
            {
                this.car.PropertyChanged -= HandlePropertyChanged;
            }

            this.car = value;
            this.car.PropertyChanged += HandlePropertyChanged;
            SetupCell();
        }
    }

    private void HandlePropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        SetupCell();
    }

    private void SetupCell()
    {
        this.TextLabel.Text = this.car.Title;
    }
}

You'll then need to create return instances of your custom cell in your UITableViewDataSource.

like image 31
Tom Gilder Avatar answered Oct 22 '22 04:10

Tom Gilder