c# - Xamarin CollectionView 在滚动时突出显示不正确的单元格

标签 c# xamarin.ios uicollectionview uicollectionviewcell

希望能帮到你。我正在使用 Xamarin for Visual Studio 2013。

我在 View Controller 上有一个 Collection View ,它将来自网络服务的数据加载到页面上的单元格中。这工作正常,数据在开始时正确显示。

滚动列表时,单元格会随机改变颜色。

任何人都可以看出为什么会发生这种情况吗?我们在此处 (CollectionView Highlights incorrect Cell When Scrolling) 上看到了示例,但似乎没有一个与此特定问题相关。

我很乐意澄清任何事情。

代码如下:

UIViewController

                public partial class UIVCKitchenView : UIViewController
                {
                public static readonly EndpointAddress EndPoint = new EndpointAddress("");

                private CateringServiceClient _client; 

               public List<KitchenViewWard> wards = new List<KitchenViewWard>();

                public UIVCKitchenView (IntPtr handle) : base (handle)
                {

                }

                public override void ViewDidLoad()
                {
                    base.ViewDidLoad();
                    InitializeHelloWorldServiceClient();
                    //todo:pass code from prefrences
                    _client.GetListAsync("01");


                }

                partial void TmpK_TouchUpInside(UIButton sender)
                {            
                }

                private static BasicHttpBinding CreateBasicHttp()
                {
                    BasicHttpBinding binding = new BasicHttpBinding
                    {
                        Name = "basicHttpBinding",
                        MaxBufferSize = 2147483647,
                        MaxReceivedMessageSize = 2147483647
                    };
                    TimeSpan timeout = new TimeSpan(0, 0, 30);
                    binding.SendTimeout = timeout;
                    binding.OpenTimeout = timeout;
                    binding.ReceiveTimeout = timeout;
                    return binding;
                }

                private void InitializeHelloWorldServiceClient()
                {
                    BasicHttpBinding binding = CreateBasicHttp();

                    _client = new CateringServiceClient(binding, EndPoint);
                    _client.GetKitchenWardListCompleted += _client_GetKitchenWardListCompleted;

                }

                void _client_GetKitchenWardListCompleted(object sender, GetKitchenWardListCompletedEventArgs e)
                {
                    if (e.Error != null)
                    {
                        BeginInvokeOnMainThread(() =>
                        {
                            //Create Alert
                            var okAlertController = UIAlertController.Create("Problem", e.Error.Message, UIAlertControllerStyle.Alert);
                            //Add Action
                            okAlertController.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                            // Present Alert
                            PresentViewController(okAlertController, true, null);

                        });
                    }
                    else if (e.Cancelled)
                    {
                        //  txtResult.Text = "Request was cancelled.";
                    }
                    else
                    {

                        List<KitchenWardList> _items = new List<KitchenWardList>(e.Result);
                        foreach (KitchenWardList item in _items)
                        {
                            KitchenViewWard _ward = new KitchenViewWard();
                            _ward.WardName = item.WardName;
                            _ward.WardStatus = item.WardStatus.ToString();
                            _ward.WardStatusId = Convert.ToInt32(item.WardStatus);

                            wards.Add(_ward);
                        }

                        BeginInvokeOnMainThread(() =>
                        {
                            UICVKitchenViewWards.RegisterClassForCell(typeof(UICVCKitchenViewWardsCell), UICVCKitchenViewWardsCell.CellID);
                            UICVKitchenViewWards.Source = new UICVCKitchenViewWardsSource(wards);
                            UICVKitchenViewWards.Delegate = new UICVKitchenViewWardsDelegate();                   
                        });
                    }
                }

            }

UICollectionViewSource 类 UIVCCKitchenViewWardsSource : UICollectionViewSource {

            public UIStoryboard MainStoryboard
            {

                get { return UIStoryboard.FromName("Main", NSBundle.MainBundle); }
            }

            //Creates an instance of viewControllerName from storyboard
            public UIViewController GetViewController(UIStoryboard storyboard, string viewControllerName)
            {
                return storyboard.InstantiateViewController(viewControllerName);
            }


            public List<KitchenViewWard> rows { get; set; }

            public UICVCKitchenViewWardsSource(List<KitchenViewWard> _rows)
            {
                rows = _rows;
            }

            public override nint NumberOfSections(UICollectionView collectionView)
            {            
                return 1;
            }

            public override nint GetItemsCount(UICollectionView collectionView, nint section)
            {         
                return rows.Count;
            }

            public override bool ShouldHighlightItem(UICollectionView collectionView, NSIndexPath indexPath)
            {         
                return true;
            }

            public override void ItemHighlighted(UICollectionView collectionView, NSIndexPath indexPath)
            {
                var cell = (UICVCKitchenViewWardsCell)collectionView.CellForItem(indexPath);
                //cell.BackgroundColor = UIColor.Yellow;
            }

            public override void ItemUnhighlighted(UICollectionView collectionView, NSIndexPath indexPath)
            {

                //var renderer = Platform.GetRenderer(page);

                var cell = (UICVCKitchenViewWardsCell)collectionView.CellForItem(indexPath);
                var UIVCKitchenViewController = GetViewController(MainStoryboard, "UIVCKitchenView");
                UIVCKitchenViewController.PerformSegue("seqShowKitchenDetails", this);

                //cell.BackgroundColor = UIColor.Orange;
            }

            public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
            {
                var cell = (UICVCKitchenViewWardsCell)collectionView.CellForItem(indexPath);
                var UIVCKitchenViewController = GetViewController(MainStoryboard, "UIVCKitchenView");
                UIVCKitchenViewController.PerformSegue("seqShowKitchenDetails", this);
            }

            public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
            {            
                var cell = (UICVCKitchenViewWardsCell)collectionView.DequeueReusableCell(UICVCKitchenViewWardsCell.CellID, indexPath);
                cell.updateCell(rows[indexPath.Row]);

                return cell;
            }

        }

UICollectionViewCell

    public partial class UICVCKitchenViewWardsCell : UICollectionViewCell
    {
    public UILabel wardName;
    public static NSString CellID = new NSString("UICVCKitchenViewWardsCell");

            [Export("initWithFrame:")]
            public UICVCKitchenViewWardsCell(CGRect frame)
                : base(frame)
            {
                ContentView.BackgroundColor = new UIColor(225f / 255f, 225f / 255f, 225f / 255f, 1f);
                ContentView.Layer.BorderWidth = 1.0f;
                ContentView.Layer.BorderColor = new CGColor(0f / 255f, 134f / 255f, 255f / 255f);

                wardName = new UILabel();            
                ContentView.AddSubviews(new UIView[] { wardName });
            }

            public void updateCell(KitchenViewWard ward)
            {
                wardName.Text = ward.WardName;            
                wardName.Frame = new CGRect(10, 25, ContentView.Bounds.Width - 20, 21);

                switch (ward.WardStatusId)
                {
                    case (int)WardOrderStatus.InProcess:
                        ContentView.BackgroundColor = new UIColor(255f / 255f, 204f / 255f, 0f / 255f, 1f);
                        break;
                    case (int)WardOrderStatus.Loaded:
                        ContentView.BackgroundColor = new UIColor(255f / 255f, 149f / 255f, 0f / 255f, 1f);
                        break;
                    case (int)WardOrderStatus.Nostatus:
                        break;
                    case (int)WardOrderStatus.OrderSent:
                        ContentView.BackgroundColor = new UIColor(90f / 255f, 200f / 255f, 250f / 255f, 1f);
                        break;
                    case (int)WardOrderStatus.Served:
                        ContentView.BackgroundColor = new UIColor(76f / 255f, 217f / 255f, 100f / 255f, 1f);

                        break;

                    default:
                        break;
                }
            }
        }

最佳答案

在你的 UITableViewCell 子类中请覆盖 prepareForReuse()并将背景颜色设置为白色或任何默认值。

UITableViewCells 得到重用,因此当它们已经分配了颜色时,您将得到一个在出队时已经着色的单元格,而不是“新鲜”单元格。

关于c# - Xamarin CollectionView 在滚动时突出显示不正确的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41365299/

相关文章:

c# - 是否应该将扩展属性添加到 C# 4.0?

C#/WCF TransactionScopeOption.必需

c# - 没有 ASP.NET 标识的 .NET Core 外部身份验证

iphone - MonoTouch.Dialog 删除表格末尾的行

ios - UIDragPreviewParametersvisiblePath 自定义形状

c# - 如何等待onPaint完成绘画(C#)

xamarin - InputTransparent=true 在 Xamarin Forms Android 中不起作用

c# - 如何检查 View 在 Xamarin.ios 的 UIScrollview 中是否可见?

ios - 设置一些气泡的最小宽度

ios - UICollectionview 数据加载问题