This repository has been archived by the owner on May 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathListViewRenderer.cs
1735 lines (1435 loc) · 51.8 KB
/
ListViewRenderer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using Foundation;
using UIKit;
using Xamarin.Forms.Internals;
using RectangleF = CoreGraphics.CGRect;
using SizeF = CoreGraphics.CGSize;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;
using Specifics = Xamarin.Forms.PlatformConfiguration.iOSSpecific.ListView;
namespace Xamarin.Forms.Platform.iOS
{
public class ListViewRenderer : ViewRenderer<ListView, UITableView>
{
const int DefaultRowHeight = 44;
ListViewDataSource _dataSource;
IVisualElementRenderer _headerRenderer;
IVisualElementRenderer _footerRenderer;
KeyboardInsetTracker _insetTracker;
RectangleF _previousFrame;
ScrollToRequestedEventArgs _requestedScroll;
FormsUITableViewController _tableViewController;
ListView ListView => Element;
ITemplatedItemsView<Cell> TemplatedItemsView => Element;
public override UIViewController ViewController => _tableViewController;
bool _disposed;
bool _usingLargeTitles;
bool? _defaultHorizontalScrollVisibility;
bool? _defaultVerticalScrollVisibility;
protected UITableViewRowAnimation InsertRowsAnimation { get; set; } = UITableViewRowAnimation.Automatic;
protected UITableViewRowAnimation DeleteRowsAnimation { get; set; } = UITableViewRowAnimation.Automatic;
protected UITableViewRowAnimation ReloadRowsAnimation { get; set; } = UITableViewRowAnimation.Automatic;
protected UITableViewRowAnimation ReloadSectionsAnimation
{
get { return _dataSource.ReloadSectionsAnimation; }
set { _dataSource.ReloadSectionsAnimation = value; }
}
[Internals.Preserve(Conditional = true)]
public ListViewRenderer()
{
}
public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
{
return Control.GetSizeRequest(widthConstraint, heightConstraint, DefaultRowHeight, DefaultRowHeight);
}
public override void LayoutSubviews()
{
_insetTracker?.OnLayoutSubviews();
base.LayoutSubviews();
double height = Bounds.Height;
double width = Bounds.Width;
if (_headerRenderer != null)
{
var e = _headerRenderer.Element;
var request = e.Measure(width, double.PositiveInfinity, MeasureFlags.IncludeMargins);
// Time for another story with Jason. Gather round children because the following Math.Ceiling will look like it's completely useless.
// You will remove it and test and find everything is fiiiiiine, but it is not fine, no it is far from fine. See iOS, or at least iOS 8
// has an issue where-by if the TableHeaderView happens to NOT be an integer height, it will add padding to the space between the content
// of the UITableView and the TableHeaderView to the tune of the difference between Math.Ceiling (height) - height. Now this seems fine
// and when you test it will be, EXCEPT that it does this every time you toggle the visibility of the UITableView causing the spacing to
// grow a little each time, which you weren't testing at all were you? So there you have it, the stupid reason we integer align here.
//
// The same technically applies to the footer, though that could hardly matter less. We just do it for fun.
Layout.LayoutChildIntoBoundingRegion(e, new Rectangle(0, 0, width, Math.Ceiling(request.Request.Height)));
Device.BeginInvokeOnMainThread(() =>
{
if (_headerRenderer != null)
Control.TableHeaderView = _headerRenderer.NativeView;
});
}
if (_footerRenderer != null)
{
var e = _footerRenderer.Element;
var request = e.Measure(width, height, MeasureFlags.IncludeMargins);
Layout.LayoutChildIntoBoundingRegion(e, new Rectangle(0, 0, width, Math.Ceiling(request.Request.Height)));
Device.BeginInvokeOnMainThread(() =>
{
if (_footerRenderer != null)
Control.TableFooterView = _footerRenderer.NativeView;
});
}
if (_requestedScroll != null && Superview != null)
{
var request = _requestedScroll;
_requestedScroll = null;
OnScrollToRequested(this, request);
}
if (_previousFrame != Frame)
{
_previousFrame = Frame;
_insetTracker?.UpdateInsets();
}
}
void DisposeSubviews(UIView view)
{
var ver = view as IVisualElementRenderer;
if (ver == null)
{
// VisualElementRenderers should implement their own dispose methods that will appropriately dispose and remove their child views.
// Attempting to do this work twice could cause a SIGSEGV (only observed in iOS8), so don't do this work here.
// Non-renderer views, such as separator lines, etc., can be removed here.
foreach (UIView subView in view.Subviews)
DisposeSubviews(subView);
view.RemoveFromSuperview();
}
view.Dispose();
}
protected override void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
if (_insetTracker != null)
{
_insetTracker.Dispose();
_insetTracker = null;
}
foreach (UIView subview in Subviews)
DisposeSubviews(subview);
if (Element != null)
{
var templatedItems = TemplatedItemsView.TemplatedItems;
templatedItems.CollectionChanged -= OnCollectionChanged;
templatedItems.GroupedCollectionChanged -= OnGroupedCollectionChanged;
}
if (_dataSource != null)
{
_dataSource.Dispose();
_dataSource = null;
}
if (_tableViewController != null)
{
_tableViewController.Dispose();
_tableViewController = null;
}
if (_headerRenderer != null)
{
_headerRenderer.Element?.DisposeModalAndChildRenderers();
_headerRenderer = null;
}
if (_footerRenderer != null)
{
_footerRenderer.Element?.DisposeModalAndChildRenderers();
_footerRenderer = null;
}
var headerView = ListView?.HeaderElement as VisualElement;
if (headerView != null)
headerView.MeasureInvalidated -= OnHeaderMeasureInvalidated;
Control?.TableHeaderView?.Dispose();
var footerView = ListView?.FooterElement as VisualElement;
if (footerView != null)
footerView.MeasureInvalidated -= OnFooterMeasureInvalidated;
Control?.TableFooterView?.Dispose();
}
_disposed = true;
base.Dispose(disposing);
}
protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
{
_requestedScroll = null;
if (e.OldElement != null)
{
var listView = e.OldElement;
var headerView = (VisualElement)listView.HeaderElement;
if (headerView != null)
headerView.MeasureInvalidated -= OnHeaderMeasureInvalidated;
var footerView = (VisualElement)listView.FooterElement;
if (footerView != null)
footerView.MeasureInvalidated -= OnFooterMeasureInvalidated;
listView.ScrollToRequested -= OnScrollToRequested;
var templatedItems = ((ITemplatedItemsView<Cell>)e.OldElement).TemplatedItems;
templatedItems.CollectionChanged -= OnCollectionChanged;
templatedItems.GroupedCollectionChanged -= OnGroupedCollectionChanged;
}
if (e.NewElement != null)
{
if (Control == null)
{
if (Forms.IsiOS11OrNewer)
{
var parentNav = e.NewElement.FindParentOfType<NavigationPage>();
_usingLargeTitles = (parentNav != null && parentNav.OnThisPlatform().PrefersLargeTitles());
}
_tableViewController = new FormsUITableViewController(e.NewElement, _usingLargeTitles);
SetNativeControl(_tableViewController.TableView);
_insetTracker = new KeyboardInsetTracker(_tableViewController.TableView, () => Control.Window, insets => Control.ContentInset = Control.ScrollIndicatorInsets = insets, point =>
{
var offset = Control.ContentOffset;
offset.Y += point.Y;
Control.SetContentOffset(offset, true);
}, this);
}
var listView = e.NewElement;
listView.ScrollToRequested += OnScrollToRequested;
var templatedItems = ((ITemplatedItemsView<Cell>)e.NewElement).TemplatedItems;
templatedItems.CollectionChanged += OnCollectionChanged;
templatedItems.GroupedCollectionChanged += OnGroupedCollectionChanged;
UpdateRowHeight();
Control.Source = _dataSource = e.NewElement.HasUnevenRows ? new UnevenListViewDataSource(e.NewElement, _tableViewController) : new ListViewDataSource(e.NewElement, _tableViewController);
UpdateHeader();
UpdateFooter();
UpdatePullToRefreshEnabled();
UpdateSpinnerColor();
UpdateIsRefreshing();
UpdateSeparatorColor();
UpdateSeparatorVisibility();
UpdateSelectionMode();
UpdateVerticalScrollBarVisibility();
UpdateHorizontalScrollBarVisibility();
var selected = e.NewElement.SelectedItem;
if (selected != null)
_dataSource.OnItemSelected(null, new SelectedItemChangedEventArgs(selected, templatedItems.GetGlobalIndexOfItem(selected)));
}
base.OnElementChanged(e);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Xamarin.Forms.ListView.RowHeightProperty.PropertyName)
UpdateRowHeight();
else if (e.PropertyName == Xamarin.Forms.ListView.IsGroupingEnabledProperty.PropertyName)
_dataSource.UpdateGrouping();
else if (e.PropertyName == Xamarin.Forms.ListView.HasUnevenRowsProperty.PropertyName)
{
Control.Source = _dataSource = Element.HasUnevenRows ? new UnevenListViewDataSource(_dataSource) : new ListViewDataSource(_dataSource);
ReloadData();
}
else if (e.PropertyName == Xamarin.Forms.ListView.IsPullToRefreshEnabledProperty.PropertyName)
UpdatePullToRefreshEnabled();
else if (e.PropertyName == Xamarin.Forms.ListView.IsRefreshingProperty.PropertyName)
UpdateIsRefreshing();
else if (e.PropertyName == Xamarin.Forms.ListView.SeparatorColorProperty.PropertyName)
UpdateSeparatorColor();
else if (e.PropertyName == Xamarin.Forms.ListView.SeparatorVisibilityProperty.PropertyName)
UpdateSeparatorVisibility();
else if (e.PropertyName == "HeaderElement")
UpdateHeader();
else if (e.PropertyName == "FooterElement")
UpdateFooter();
else if (e.PropertyName == "RefreshAllowed")
UpdatePullToRefreshEnabled();
else if (e.PropertyName == Xamarin.Forms.ListView.SelectionModeProperty.PropertyName)
UpdateSelectionMode();
else if (e.PropertyName == Xamarin.Forms.ListView.RefreshControlColorProperty.PropertyName)
UpdateSpinnerColor();
else if (e.PropertyName == ScrollView.VerticalScrollBarVisibilityProperty.PropertyName)
UpdateVerticalScrollBarVisibility();
else if (e.PropertyName == ScrollView.HorizontalScrollBarVisibilityProperty.PropertyName)
UpdateHorizontalScrollBarVisibility();
}
public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection)
{
base.TraitCollectionDidChange(previousTraitCollection);
#if __XCODE11__
// Make sure the cells adhere to changes UI theme
if (Forms.IsiOS13OrNewer && previousTraitCollection?.UserInterfaceStyle != TraitCollection.UserInterfaceStyle)
ReloadData();
#endif
}
NSIndexPath[] GetPaths(int section, int index, int count)
{
var paths = new NSIndexPath[count];
for (var i = 0; i < paths.Length; i++)
paths[i] = NSIndexPath.FromRowSection(index + i, section);
return paths;
}
UITableViewScrollPosition GetScrollPosition(ScrollToPosition position)
{
switch (position)
{
case ScrollToPosition.Center:
return UITableViewScrollPosition.Middle;
case ScrollToPosition.End:
return UITableViewScrollPosition.Bottom;
case ScrollToPosition.Start:
return UITableViewScrollPosition.Top;
case ScrollToPosition.MakeVisible:
default:
return UITableViewScrollPosition.None;
}
}
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
UpdateItems(e, 0, true);
}
void OnFooterMeasureInvalidated(object sender, EventArgs eventArgs)
{
double width = Bounds.Width;
if (width == 0)
return;
var footerView = (VisualElement)sender;
var request = footerView.Measure(width, double.PositiveInfinity, MeasureFlags.IncludeMargins);
Layout.LayoutChildIntoBoundingRegion(footerView, new Rectangle(0, 0, width, request.Request.Height));
Control.TableFooterView = _footerRenderer.NativeView;
}
void OnGroupedCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
var til = (TemplatedItemsList<ItemsView<Cell>, Cell>)sender;
var templatedItems = TemplatedItemsView.TemplatedItems;
var groupIndex = templatedItems.IndexOf(til.HeaderContent);
UpdateItems(e, groupIndex, false);
}
void OnHeaderMeasureInvalidated(object sender, EventArgs eventArgs)
{
double width = Bounds.Width;
if (width == 0)
return;
var headerView = (VisualElement)sender;
var request = headerView.Measure(width, double.PositiveInfinity, MeasureFlags.IncludeMargins);
Layout.LayoutChildIntoBoundingRegion(headerView, new Rectangle(0, 0, width, request.Request.Height));
Control.TableHeaderView = _headerRenderer.NativeView;
}
void OnScrollToRequested(object sender, ScrollToRequestedEventArgs e)
{
if (Superview == null)
{
_requestedScroll = e;
return;
}
var position = GetScrollPosition(e.Position);
var scrollArgs = (ITemplatedItemsListScrollToRequestedEventArgs)e;
var templatedItems = TemplatedItemsView.TemplatedItems;
if (Element.IsGroupingEnabled)
{
var result = templatedItems.GetGroupAndIndexOfItem(scrollArgs.Group, scrollArgs.Item);
if (result.Item1 != -1 && result.Item2 != -1)
Control.ScrollToRow(NSIndexPath.FromRowSection(result.Item2, result.Item1), position, e.ShouldAnimate);
}
else
{
var index = templatedItems.GetGlobalIndexOfItem(scrollArgs.Item);
if (index != -1)
{
Control.Layer.RemoveAllAnimations();
//iOS11 hack
if (Forms.IsiOS11OrNewer)
this.QueueForLater(() =>
{
if (Control != null && !_disposed)
Control.ScrollToRow(NSIndexPath.FromRowSection(index, 0), position, e.ShouldAnimate);
});
else
Control.ScrollToRow(NSIndexPath.FromRowSection(index, 0), position, e.ShouldAnimate);
}
}
}
void UpdateFooter()
{
var footer = ListView.FooterElement;
var footerView = (View)footer;
if (footerView != null)
{
if (_footerRenderer != null)
{
_footerRenderer.Element.MeasureInvalidated -= OnFooterMeasureInvalidated;
var reflectableType = _footerRenderer as System.Reflection.IReflectableType;
var rendererType = reflectableType != null ? reflectableType.GetTypeInfo().AsType() : _footerRenderer.GetType();
if (footer != null && rendererType == Internals.Registrar.Registered.GetHandlerTypeForObject(footer))
{
_footerRenderer.SetElement(footerView);
return;
}
Control.TableFooterView = null;
_footerRenderer.Element?.DisposeModalAndChildRenderers();
_footerRenderer.Dispose();
_footerRenderer = null;
}
_footerRenderer = Platform.CreateRenderer(footerView);
Platform.SetRenderer(footerView, _footerRenderer);
double width = Bounds.Width;
var request = footerView.Measure(width, double.PositiveInfinity, MeasureFlags.IncludeMargins);
Layout.LayoutChildIntoBoundingRegion(footerView, new Rectangle(0, 0, width, request.Request.Height));
Control.TableFooterView = _footerRenderer.NativeView;
footerView.MeasureInvalidated += OnFooterMeasureInvalidated;
}
else if (_footerRenderer != null)
{
Control.TableFooterView = null;
_footerRenderer.Element.MeasureInvalidated -= OnFooterMeasureInvalidated;
_footerRenderer.Element?.DisposeModalAndChildRenderers();
_footerRenderer.Dispose();
_footerRenderer = null;
}
}
void UpdateHeader()
{
var header = ListView.HeaderElement;
var headerView = (View)header;
if (headerView != null)
{
if (_headerRenderer != null)
{
_headerRenderer.Element.MeasureInvalidated -= OnHeaderMeasureInvalidated;
var reflectableType = _headerRenderer as System.Reflection.IReflectableType;
var rendererType = reflectableType != null ? reflectableType.GetTypeInfo().AsType() : _headerRenderer.GetType();
if (header != null && rendererType == Internals.Registrar.Registered.GetHandlerTypeForObject(header))
{
_headerRenderer.SetElement(headerView);
return;
}
Control.TableHeaderView = null;
_headerRenderer.Element?.DisposeModalAndChildRenderers();
_headerRenderer.Dispose();
_headerRenderer = null;
}
_headerRenderer = Platform.CreateRenderer(headerView);
// This will force measure to invalidate, which we haven't hooked up to yet because we are smarter!
Platform.SetRenderer(headerView, _headerRenderer);
double width = Bounds.Width;
var request = headerView.Measure(width, double.PositiveInfinity, MeasureFlags.IncludeMargins);
Layout.LayoutChildIntoBoundingRegion(headerView, new Rectangle(0, 0, width, request.Request.Height));
Control.TableHeaderView = _headerRenderer.NativeView;
headerView.MeasureInvalidated += OnHeaderMeasureInvalidated;
}
else if (_headerRenderer != null)
{
Control.TableHeaderView = null;
_headerRenderer.Element.MeasureInvalidated -= OnHeaderMeasureInvalidated;
_headerRenderer.Element?.DisposeModalAndChildRenderers();
_headerRenderer.Dispose();
_headerRenderer = null;
}
}
void UpdateIsRefreshing()
{
var refreshing = Element.IsRefreshing;
if (_tableViewController != null)
_tableViewController.UpdateIsRefreshing(refreshing);
}
void UpdateItems(NotifyCollectionChangedEventArgs e, int section, bool resetWhenGrouped)
{
var exArgs = e as NotifyCollectionChangedEventArgsEx;
if (exArgs != null)
_dataSource.Counts[section] = exArgs.Count;
// This means the UITableView hasn't rendered any cells yet
// so there's no need to synchronize the rows on the UITableView
if (Control.IndexPathsForVisibleRows == null && e.Action != NotifyCollectionChangedAction.Reset)
return;
var groupReset = resetWhenGrouped && Element.IsGroupingEnabled;
// We can't do this check on grouped lists because the index doesn't match the number of rows in a section.
// Likewise, we can't do this check on lists using RecycleElement because the number of rows in a section will remain constant because they are reused.
if (!groupReset && Element.CachingStrategy == ListViewCachingStrategy.RetainElement)
{
var lastIndex = Control.NumberOfRowsInSection(section);
if (e.NewStartingIndex > lastIndex || e.OldStartingIndex > lastIndex)
throw new ArgumentException(
$"Index '{Math.Max(e.NewStartingIndex, e.OldStartingIndex)}' is greater than the number of rows '{lastIndex}'.");
}
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
if (e.NewStartingIndex == -1 || groupReset)
goto case NotifyCollectionChangedAction.Reset;
InsertRows(e.NewStartingIndex, e.NewItems.Count, section);
break;
case NotifyCollectionChangedAction.Remove:
if (e.OldStartingIndex == -1 || groupReset)
goto case NotifyCollectionChangedAction.Reset;
DeleteRows(e.OldStartingIndex, e.OldItems.Count, section);
if (TemplatedItemsView.TemplatedItems.Count == 0)
InvalidateCellCache();
break;
case NotifyCollectionChangedAction.Move:
if (e.OldStartingIndex == -1 || e.NewStartingIndex == -1 || groupReset)
goto case NotifyCollectionChangedAction.Reset;
MoveRows(e.NewStartingIndex, e.OldStartingIndex, e.OldItems.Count, section);
if (e.OldStartingIndex == 0)
InvalidateCellCache();
break;
case NotifyCollectionChangedAction.Replace:
if (e.OldStartingIndex == -1 || groupReset)
goto case NotifyCollectionChangedAction.Reset;
ReloadRows(e.OldStartingIndex, e.OldItems.Count, section);
if (e.OldStartingIndex == 0)
InvalidateCellCache();
break;
case NotifyCollectionChangedAction.Reset:
InvalidateCellCache();
ReloadData();
return;
}
}
void InsertRows(int newStartingIndex, int newItemsCount, int section)
{
var action = new Action(() =>
{
Control.BeginUpdates();
Control.InsertRows(GetPaths(section, newStartingIndex, newItemsCount), InsertRowsAnimation);
Control.EndUpdates();
});
if (Element.OnThisPlatform().RowAnimationsEnabled())
action.Invoke();
else
PerformWithoutAnimation(() => { action.Invoke(); });
}
void DeleteRows(int oldStartingIndex, int oldItemsCount, int section)
{
var action = new Action(() =>
{
Control.BeginUpdates();
Control.DeleteRows(GetPaths(section, oldStartingIndex, oldItemsCount), DeleteRowsAnimation);
Control.EndUpdates();
});
if (Element.OnThisPlatform().RowAnimationsEnabled())
action.Invoke();
else
PerformWithoutAnimation(() => { action.Invoke(); });
}
void MoveRows(int newStartingIndex, int oldStartingIndex, int oldItemsCount, int section)
{
var action = new Action(() =>
{
Control.BeginUpdates();
for (var i = 0; i < oldItemsCount; i++)
{
var oldIndex = oldStartingIndex;
var newIndex = newStartingIndex;
if (newStartingIndex < oldStartingIndex)
{
oldIndex += i;
newIndex += i;
}
Control.MoveRow(NSIndexPath.FromRowSection(oldIndex, section), NSIndexPath.FromRowSection(newIndex, section));
}
Control.EndUpdates();
});
if (Element.OnThisPlatform().RowAnimationsEnabled())
action.Invoke();
else
PerformWithoutAnimation(() => { action.Invoke(); });
}
void ReloadRows(int oldStartingIndex, int oldItemsCount, int section)
{
var action = new Action(() =>
{
Control.BeginUpdates();
Control.ReloadRows(GetPaths(section, oldStartingIndex, oldItemsCount), ReloadRowsAnimation);
Control.EndUpdates();
});
if (Element.OnThisPlatform().RowAnimationsEnabled())
action.Invoke();
else
PerformWithoutAnimation(() => { action.Invoke(); });
}
void ReloadData()
{
if (Element.OnThisPlatform().RowAnimationsEnabled())
Control.ReloadData();
else
PerformWithoutAnimation(() => { Control.ReloadData(); });
}
void InvalidateCellCache()
{
_dataSource.InvalidatePrototypicalCellCache();
}
void UpdatePullToRefreshEnabled()
{
if (_tableViewController != null)
{
var isPullToRequestEnabled = Element.IsPullToRefreshEnabled && ListView.RefreshAllowed;
_tableViewController.UpdatePullToRefreshEnabled(isPullToRequestEnabled);
}
}
void UpdateRowHeight()
{
var rowHeight = Element.RowHeight;
if (Element.HasUnevenRows && rowHeight == -1)
Control.RowHeight = UITableView.AutomaticDimension;
else
Control.RowHeight = rowHeight <= 0 ? DefaultRowHeight : rowHeight;
}
void UpdateSeparatorColor()
{
var color = Element.SeparatorColor;
// ...and Steve said to the unbelievers the separator shall be gray, and gray it was. The unbelievers looked on, and saw that it was good, and
// they went forth and documented the default color. The holy scripture still reflects this default.
// Defined here: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/#//apple_ref/occ/instp/UITableView/separatorColor
Control.SeparatorColor = color.ToUIColor(ColorExtensions.SeparatorColor);
}
void UpdateSeparatorVisibility()
{
var visibility = Element.SeparatorVisibility;
switch (visibility)
{
case SeparatorVisibility.Default:
Control.SeparatorStyle = UITableViewCellSeparatorStyle.SingleLine;
break;
case SeparatorVisibility.None:
Control.SeparatorStyle = UITableViewCellSeparatorStyle.None;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
void UpdateSelectionMode()
{
if (Element.SelectionMode == ListViewSelectionMode.None)
{
Element.SelectedItem = null;
var selectedIndexPath = Control.IndexPathForSelectedRow;
if (selectedIndexPath != null)
Control.DeselectRow(selectedIndexPath, false);
}
}
void UpdateSpinnerColor()
{
var color = Element.RefreshControlColor;
if (_tableViewController != null)
_tableViewController.UpdateRefreshControlColor(color == Color.Default ? null : color.ToUIColor());
}
void UpdateVerticalScrollBarVisibility()
{
if (_defaultVerticalScrollVisibility == null)
_defaultVerticalScrollVisibility = Control.ShowsVerticalScrollIndicator;
switch (Element.VerticalScrollBarVisibility)
{
case (ScrollBarVisibility.Always):
Control.ShowsVerticalScrollIndicator = true;
break;
case (ScrollBarVisibility.Never):
Control.ShowsVerticalScrollIndicator = false;
break;
case (ScrollBarVisibility.Default):
Control.ShowsVerticalScrollIndicator = (bool)_defaultVerticalScrollVisibility;
break;
}
}
void UpdateHorizontalScrollBarVisibility()
{
if (_defaultHorizontalScrollVisibility == null)
_defaultHorizontalScrollVisibility = Control.ShowsHorizontalScrollIndicator;
switch (Element.HorizontalScrollBarVisibility)
{
case (ScrollBarVisibility.Always):
Control.ShowsHorizontalScrollIndicator = true;
break;
case (ScrollBarVisibility.Never):
Control.ShowsHorizontalScrollIndicator = false;
break;
case (ScrollBarVisibility.Default):
Control.ShowsHorizontalScrollIndicator = (bool)_defaultHorizontalScrollVisibility;
break;
}
}
internal class UnevenListViewDataSource : ListViewDataSource
{
IVisualElementRenderer _prototype;
bool _disposed;
Dictionary<object, Cell> _prototypicalCellByTypeOrDataTemplate = new Dictionary<object, Cell>();
public UnevenListViewDataSource(ListView list, FormsUITableViewController uiTableViewController) : base(list, uiTableViewController)
{
}
public UnevenListViewDataSource(ListViewDataSource source) : base(source)
{
}
nfloat GetEstimatedRowHeight(UITableView table)
{
if (List.RowHeight != -1)
{
// Not even sure we need this case; A list with HasUnevenRows and a RowHeight doesn't make a ton of sense
// Anyway, no need for an estimate, because the heights we'll use are known
return 0;
}
var templatedItems = TemplatedItemsView.TemplatedItems;
if (templatedItems.Count == 0)
{
// No cells to provide an estimate, use the default row height constant
return DefaultRowHeight;
}
// We're going to base our estimate off of the first cell
var isGroupingEnabled = List.IsGroupingEnabled;
if (isGroupingEnabled)
templatedItems = templatedItems.GetGroup(0);
object item = null;
if (templatedItems == null || templatedItems.ListProxy.TryGetValue(0, out item) == false)
return DefaultRowHeight;
var firstCell = templatedItems.ActivateContent(0, item);
// Let's skip this optimization for grouped lists. It will likely cause more trouble than it's worth.
if (firstCell?.Height > 0 && !isGroupingEnabled)
{
// Seems like we've got cells which already specify their height; since the heights are known,
// we don't need to use estimatedRowHeight at all; zero will disable it and use the known heights.
// However, not setting the EstimatedRowHeight will drastically degrade performance with large lists.
// In this case, we will cache the specified cell heights asynchronously, which will be returned one time on
// table load by EstimatedHeight.
return 0;
}
return CalculateHeightForCell(table, firstCell);
}
internal override void InvalidatingPrototypicalCellCache()
{
ClearPrototype();
_prototypicalCellByTypeOrDataTemplate.Clear();
}
protected override void UpdateEstimatedRowHeight(UITableView tableView)
{
var estimatedRowHeight = GetEstimatedRowHeight(tableView);
//if we are providing 0 we are disabling EstimatedRowHeight,
//this works fine on newer versions, but iOS10 it will cause a crash so we leave the default value
if (estimatedRowHeight > 0 || (estimatedRowHeight == 0 && Forms.IsiOS11OrNewer))
tableView.EstimatedRowHeight = estimatedRowHeight;
}
internal Cell GetPrototypicalCell(NSIndexPath indexPath)
{
var itemTypeOrDataTemplate = default(object);
var cachingStrategy = List.CachingStrategy;
if (cachingStrategy == ListViewCachingStrategy.RecycleElement)
itemTypeOrDataTemplate = GetDataTemplateForPath(indexPath);
else if (cachingStrategy == ListViewCachingStrategy.RecycleElementAndDataTemplate)
itemTypeOrDataTemplate = GetItemTypeForPath(indexPath);
else // ListViewCachingStrategy.RetainElement
return GetCellForPath(indexPath);
if (itemTypeOrDataTemplate == null)
itemTypeOrDataTemplate = typeof(TextCell);
if (!_prototypicalCellByTypeOrDataTemplate.TryGetValue(itemTypeOrDataTemplate, out Cell protoCell))
{
// cache prototypical cell by item type; Items of the same Type share
// the same DataTemplate (this is enforced by RecycleElementAndDataTemplate)
protoCell = GetCellForPath(indexPath);
_prototypicalCellByTypeOrDataTemplate[itemTypeOrDataTemplate] = protoCell;
}
var templatedItems = GetTemplatedItemsListForPath(indexPath);
return templatedItems.UpdateContent(protoCell, indexPath.Row);
}
public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
{
// iOS may ask for a row we have just deleted and hence cannot rebind in order to measure height.
if (!IsValidIndexPath(indexPath))
return DefaultRowHeight;
var cell = GetPrototypicalCell(indexPath);
if (List.RowHeight == -1 && cell.Height == -1 && cell is ViewCell)
return UITableView.AutomaticDimension;
var renderHeight = cell.RenderHeight;
return renderHeight > 0 ? (nfloat)renderHeight : DefaultRowHeight;
}
internal nfloat CalculateHeightForCell(UITableView tableView, Cell cell)
{
var viewCell = cell as ViewCell;
if (viewCell != null && viewCell.View != null)
{
var target = viewCell.View;
if (_prototype == null)
_prototype = Platform.CreateRenderer(target);
else
_prototype.SetElement(target);
Platform.SetRenderer(target, _prototype);
var req = target.Measure(tableView.Frame.Width, double.PositiveInfinity, MeasureFlags.IncludeMargins);
target.ClearValue(Platform.RendererProperty);
foreach (Element descendant in target.Descendants())
{
IVisualElementRenderer renderer = Platform.GetRenderer(descendant as VisualElement);
// Clear renderer from descendent; this will not happen in Dispose as normal because we need to
// unhook the Element from the renderer before disposing it.
descendant.ClearValue(Platform.RendererProperty);
renderer?.Dispose();
renderer = null;
}
// Let the EstimatedHeight method know to use this value.
// Much more efficient than checking the value each time.
//_useEstimatedRowHeight = true;
var height = (nfloat)req.Request.Height;
return height > 1 ? height : DefaultRowHeight;
}
var renderHeight = cell.RenderHeight;
return renderHeight > 0 ? (nfloat)renderHeight : DefaultRowHeight;
}
protected override void Dispose(bool disposing)
{
if (_disposed)
return;
_disposed = true;
if (disposing)
{
ClearPrototype();
}
base.Dispose(disposing);
}
void ClearPrototype()
{
if (_prototype != null)
{
var element = _prototype.Element;
element?.ClearValue(Platform.RendererProperty);
_prototype?.Dispose();
_prototype = null;
}
}
}
internal class ListViewDataSource : UITableViewSource
{
const int DefaultItemTemplateId = 1;
static int s_dataTemplateIncrementer = 2; // lets start at not 0 because
readonly nfloat _defaultSectionHeight;
Dictionary<DataTemplate, int> _templateToId = new Dictionary<DataTemplate, int>();
UITableView _uiTableView;
FormsUITableViewController _uiTableViewController;
protected ListView List;
protected ITemplatedItemsView<Cell> TemplatedItemsView => List;
bool _isDragging;
bool _setupSelection;
bool _selectionFromNative;
bool _disposed;
bool _wasEmpty;
bool _estimatedRowHeight;
public UITableViewRowAnimation ReloadSectionsAnimation { get; set; } = UITableViewRowAnimation.Automatic;
public ListViewDataSource(ListViewDataSource source)
{
_uiTableViewController = source._uiTableViewController;
List = source.List;
_uiTableView = source._uiTableView;
_defaultSectionHeight = source._defaultSectionHeight;
_selectionFromNative = source._selectionFromNative;
Counts = new Dictionary<int, int>();
}
public ListViewDataSource(ListView list, FormsUITableViewController uiTableViewController)
{
_uiTableViewController = uiTableViewController;
_uiTableView = uiTableViewController.TableView;
_defaultSectionHeight = DefaultRowHeight;
List = list;
List.ItemSelected += OnItemSelected;
UpdateShortNameListener();
Counts = new Dictionary<int, int>();
}
public Dictionary<int, int> Counts { get; set; }
UIColor DefaultBackgroundColor => UIColor.Clear;