How can I change the background color of a ListView's selected item in Xamarin.Forms with iOS 15/16?

29 views Asked by At

How can I change background color of items of a ListView's selected item in the latest version of Xamarin.Forms for iOS platform?

For old iOS platform, the selected item's background color can be changed by writing a custom ViewCellRenderer:

public class ViewCellRenderer : Xamarin.Forms.Platform.iOS.ViewCellRenderer
    {
        public ViewCellRenderer()
        {
        }

        public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
        {
            UITableViewCell cell = base.GetCell(item, reusableCell, tv);
            ListView listView = cell?.Parent as ListView;
            if (listView != null && listView.SelectionMode == ListViewSelectionMode.None)
            {
                uiCell.SelectionStyle = UITableViewCellSelectionStyle.None;
            }
            else
            {
                uiCell.SelectedBackgroundView = new UIView
                {
                    BackgroundColor = ColorCache.ListViewSelectedItemBackgroundColor.ToUIColor()
                };
            }
            
            return cell;
        }
    }

But for the latest iOS 15/16, this method does not work again.

1

There are 1 answers

0
Mark.Fang On

After fetching the view structure from Xcode by run the app to the simulator, I found that the new iOS applys the gray background color like this:

>UITableView->Xamarin_Forms_Platform_iOS_ContextActionCell->UITableViewCellSelectedBackground

Then you can add a new ListViewRender to override the default selectedBackgroundView's backgroundColor value:

public class ListViewRenderer : Xamarin.Forms.Platform.iOS.ListViewRenderer { public ListViewRenderer() { }

public override void LayoutSubviews()
{
    base.LayoutSubviews();

    var controller = this.ViewController as UITableViewController;
    if (controller != null)
    {
        var tableView = controller.TableView;
        if (tableView != null && tableView.Subviews != null)
        {
            tableView.LayoutSubviews();//For lower iOS version, this line must add, otherwise it can not find any UITableViewCell

            var backgroundColor = Color.Red.ToUIColor();
            foreach (var subview in tableView.Subviews)
            {
                if (subview is UITableViewCell tableViewCell)
                {
                    tableViewCell.SelectedBackgroundView = new UIView
                    {
                        BackgroundColor = backgroundColor
                    };
                    tableViewCell.MultipleSelectionBackgroundView = new UIView
                    {
                        BackgroundColor = backgroundColor
                    };
                }
            }
        }
    }
} }