简体   繁体   中英

Xamarin.Forms iOS listview selected item color

I need to change the selected item color of a listview in my Xamarin.Forms app. So I created a custom renderer...

PCL C#:

public class DarkViewCell : ViewCell {}

PCL XAML:

<ListView>
  <ListView.ItemTemplate>
    <DataTemplate>
      <local:DarkViewCell>
        <ViewCell.View>
          ... Stuff ...
        </ViewCell.View>
      </local:DarkViewCell>            
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

iOS

public class DarkViewCellRenderer : ViewCellRenderer
{
    private UIView bgView;

    public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
    {
        var cell = base.GetCell(item, reusableCell, tv);

        cell.BackgroundColor = UIColor.Black;
        cell.TextLabel.TextColor = UIColor.White;

        if (bgView == null)
        {
            bgView = new UIView(cell.SelectedBackgroundView.Bounds);
            bgView.Layer.BackgroundColor = UIColor.FromRGB(48,48,48).CGColor;
            bgView.Layer.BorderColor = UIColor.FromRGB(48, 48, 48).CGColor;
            bgView.Layer.BorderWidth = 2.0f;
        }

        cell.SelectedBackgroundView = bgView;

        return cell;
    }
}

But is not working. I also tried to change the SelectionStyle but nothing...

EDIT

In a new project it works. And the code is the same

I'm not 100% sure but, I removed

<x:Arguments>
    <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
</x:Arguments>

and it started working.

Try setting:

public override UITableViewCell GetCell(Cell item, UITableView tv)
{
    var cell = base.GetCell(item, tv);
    cell.SelectedBackgroundView = new UIView() { BackgroundColor = UIColor.Black };
    return cell;
}

Update: I just used your code in a dummy project and it works as it should. Did you add the assembly attribute to register the custom renderer?

[assembly: ExportRenderer(typeof(DarkViewCell), typeof(DarkViewCellRenderer))]
namespace MyProject.iOS
{
    public class DarkViewCellRenderer : ViewCellRenderer
    {
    }
}

I had a similar issue recently, I found the best way to set the background color of a cell is to use the cells ContentView

Try using the following in your GetCell method

cell.ContentView.BackgroundColor = UIColor.Black;

Follow below code it's working for me

 public override UITableViewCell GetCell(Cell item, UITableView tv)
  {
    var cell = base.GetCell(item, tv);

     cell.SelectedBackgroundView = new UIView {
     BackgroundColor = UIColor.DarkGray,
   };
  return cell;
 }

Below link is useful for you

Xamarin.Forms ListView: Set the highlight color of a tapped item

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM