summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Platform.iOS/Renderers/CarouselViewRenderer.cs
blob: 84f57a91561ecf541fa517ab012fd784540dfb8a (plain)
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
#if __UNIFIED__
using UIKit;
using Foundation;
#else
using MonoTouch.UIKit;
using MonoTouch.Foundation;
#endif
#if __UNIFIED__
using RectangleF = CoreGraphics.CGRect;
using SizeF = CoreGraphics.CGSize;
using PointF = CoreGraphics.CGPoint;

#else
using nfloat=System.Single;
using nint=System.Int32;
using nuint=System.UInt32;
#endif

namespace Xamarin.Forms.Platform.iOS
{
	/// <summary>
	///     UICollectionView visualizes a collection of data. UICollectionViews are created indirectly by first creating a
	///     CarouselViewController from which the CollectionView is accessed via the CollectionView property.
	///     The CarouselViewController functionality is exposed through a set of interfaces (aka "conforms to" in the Apple
	///     docs).
	///     When Xamarin exposed CarouselViewRenderer the following interfaces where implemented as virtual methods:
	///     UICollectionViewSource
	///     UIScrollViewDelegate
	///     UICollectionViewDelegate		Allow you to manage the selection and highlighting of items in a collection view
	///     UICollectionViewDataSource		Creation and configuration of cells and supplementary views used to display data
	///     The interfaces only implement required method while the UICollectionView exposes optional methods via
	///     ExportAttribute.
	///     The C# method name may be aliased. For example, C# "GetCell" maps to obj-C "CellForItemAtIndexPath".
#pragma warning disable 1584
	///     <seealso cref="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionView_class/" />
#pragma warning restore 1584
	/// </summary>
	public class CarouselViewRenderer : ViewRenderer<CarouselView, UICollectionView>
	{
		#region Static Fields
		const int DefaultMinimumDimension = 44;
		static readonly UIColor DefaultBackgroundColor = UIColor.White;
		#endregion

		#region Fields
		// As on Android, ScrollToPostion from 0 to 2 should not raise OnPositionChanged for 1
		// Tracking the _targetPosition allows for skipping events for intermediate positions
		int? _targetPosition;

		int _position;
		CarouselViewController _controller;
		#endregion

		new UIScrollView Control
		{
			get
			{
				Initialize();
				return base.Control;
			}
		}
		ICarouselViewController Controller
		{
			get { return Element; }
		}
		void Initialize()
		{
			// cache hit? 
			var carouselView = base.Control;
			if (carouselView != null)
				return;

			_controller = new CarouselViewController(
				renderer: this,
				initialPosition: Element.Position
			);

			// hook up on position changed event
			// not ideal; the event is raised upon releasing the swipe instead of animation completion
			_controller.OnWillDisplayCell += o => OnPositionChange(o);

			// populate cache
			SetNativeControl(_controller.CollectionView);
		}

		void OnItemChange(int position)
		{
			var item = Controller.GetItem(position);
			Controller.SendSelectedItemChanged(item);
		}
		void OnPositionChange(int position)
		{
			if (position == _position)
				return;

			if (_targetPosition != null && position != _targetPosition)
				return;

			_targetPosition = null;
			_position = position;
			Element.Position = _position;

			Controller.SendSelectedPositionChanged(position);
			OnItemChange(position);
			return;
		}
		void ScrollToPosition(int position, bool animated = true)
		{
			if (position == _position)
				return;

			_targetPosition = position;
			_controller.ScrollToPosition(position, animated);
		}
		void OnCollectionChanged(object source, NotifyCollectionChangedEventArgs e)
		{
			switch (e.Action)
			{
				case NotifyCollectionChangedAction.Add:
					_controller.ReloadData();

					if (e.NewStartingIndex <= _position)
						ShiftPosition(e.NewItems.Count);

					break;

				case NotifyCollectionChangedAction.Move:
					for (var i = 0; i < e.NewItems.Count; i++)
					{
						_controller.MoveItem(
							oldPosition: e.OldStartingIndex + i,
							newPosition: e.NewStartingIndex + i
						);
					}
					break;

				case NotifyCollectionChangedAction.Remove:
					if (Element.Count == 0)
						throw new InvalidOperationException("CarouselView must retain a least one item.");

					if (e.OldStartingIndex == _position)
					{
						_controller.DeleteItems(
							Enumerable.Range(e.OldStartingIndex, e.OldItems.Count)
						);
						if (_position == Element.Count)
							_position--;
						OnItemChange(_position);
					}

					else
					{
						_controller.ReloadData();

						if (e.OldStartingIndex < _position)
							ShiftPosition(-e.OldItems.Count);
					}

					break;

				case NotifyCollectionChangedAction.Replace:
					_controller.ReloadItems(
						Enumerable.Range(e.OldStartingIndex, e.OldItems.Count)
					);
					break;

				case NotifyCollectionChangedAction.Reset:
					_controller.ReloadData();
					break;

				default:
					throw new Exception();
			}
		}
		void ShiftPosition(int offset)
		{
			// By default the position remains the same which causes an animation in the case
			// of the added/removed position preceding the current position. I prefer the constructed
			// Android behavior whereby the item remains the same and the position changes.
			ScrollToPosition(_position + offset, false);
		}

		protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "Position" && _position != Element.Position)
				// not ideal; the event is raised before the animation to move completes (or even starts)
				ScrollToPosition(Element.Position);

			base.OnElementPropertyChanged(sender, e);
		}
		protected override void OnElementChanged(ElementChangedEventArgs<CarouselView> e)
		{
			base.OnElementChanged(e);

			CarouselView oldElement = e.OldElement;
			CarouselView newElement = e.NewElement;
			if (oldElement != null)
			{
				e.OldElement.CollectionChanged -= OnCollectionChanged;
			}

			if (newElement != null)
			{
				if (Control == null)
				{
					Initialize();
				}

				// initialize properties
				_position = Element.Position;

				// hook up crud events
				Element.CollectionChanged += OnCollectionChanged;
			}
		}

		public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
		{
			return Control.GetSizeRequest(widthConstraint, heightConstraint, DefaultMinimumDimension, DefaultMinimumDimension);
		}
	}

	internal sealed class CarouselViewController : UICollectionViewController
	{
		new sealed class Layout : UICollectionViewFlowLayout {
			static readonly nfloat ZeroMinimumInteritemSpacing = 0;
			static readonly nfloat ZeroMinimumLineSpacing = 0;

			public Layout(UICollectionViewScrollDirection scrollDirection) {
				ScrollDirection = scrollDirection;
				MinimumInteritemSpacing = ZeroMinimumInteritemSpacing;
				MinimumLineSpacing = ZeroMinimumLineSpacing;
			}
		}
		sealed class Cell : UICollectionViewCell
		{
			IItemViewController _controller;
			int _position;
			IVisualElementRenderer _renderer;
			View _view;

			void Bind(object item, int position)
			{
				//if (position != this.position)
				//	controller.SendPositionDisappearing (this.position);

				_position = position;
				OnBind?.Invoke(position);

				_controller.BindView(_view, item);
			}

			[Export("initWithFrame:")]
			internal Cell(RectangleF frame) : base(frame)
			{
				_position = -1;
			}
			internal void Initialize(IItemViewController controller, object itemType, object item, int position)
			{
				_position = position;

				if (_controller == null)
				{
					_controller = controller;

					// create view
					_view = controller.CreateView(itemType);

					// bind view
					Bind(item, position);

					// render view
					_renderer = Platform.CreateRenderer(_view);
					Platform.SetRenderer(_view, _renderer);

					// attach view
					var uiView = _renderer.NativeView;
					ContentView.AddSubview(uiView);
				}
				else
					Bind(item, position);
			}

			public Action<int> OnBind;
			public override void LayoutSubviews()
			{
				base.LayoutSubviews();

				_renderer.Element.Layout(new Rectangle(0, 0, ContentView.Frame.Width, ContentView.Frame.Height));
			}
		}

		readonly Dictionary<object, int> _typeIdByType;
		CarouselViewRenderer _renderer;
		int _nextItemTypeId;
		int _initialPosition;

		internal CarouselViewController(
			CarouselViewRenderer renderer, 
			int initialPosition)
			: base(new Layout(UICollectionViewScrollDirection.Horizontal))
		{
			_renderer = renderer;
			_typeIdByType = new Dictionary<object, int>();
			_nextItemTypeId = 0;
			_initialPosition = initialPosition;
		}

		CarouselViewRenderer Renderer => _renderer;
		CarouselView Element => _renderer.Element;
		ICarouselViewController Controller => Element;

		[Export("collectionView:layout:sizeForItemAtIndexPath:")]
		SizeF GetSizeForItem(
			UICollectionView collectionView,
			UICollectionViewLayout layout, 
			NSIndexPath indexPath)
		{
			return collectionView.Frame.Size;
		}

		internal Action<int> OnBind;
		internal Action<int> OnWillDisplayCell;

		public override void WillDisplayCell(UICollectionView collectionView, UICollectionViewCell cell, NSIndexPath indexPath)
		{
			if (_initialPosition != 0) {
				ScrollToPosition(_initialPosition, false);
				_initialPosition = 0;
				return;
			}

			var index = indexPath.Row;
			OnWillDisplayCell?.Invoke(index);
		}
		public override nint NumberOfSections(UICollectionView collectionView)
		{
			return 1;
		}
		public override void ViewDidLoad()
		{
			base.ViewDidLoad();

			CollectionView.PagingEnabled = true;
			CollectionView.BackgroundColor = UIColor.Clear;
		}
		public override nint GetItemsCount(UICollectionView collectionView, nint section)
		{
			var result = Element.Count;
			return result;
		}
		public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
		{
			var index = indexPath.Row;

			if (_initialPosition != 0)
				index = _initialPosition;

			var item = Controller.GetItem(index);
			var itemType = Controller.GetItemType(item);

			var itemTypeId = default(int);
			if (!_typeIdByType.TryGetValue(itemType, out itemTypeId))
			{
				_typeIdByType[itemType] = itemTypeId = _nextItemTypeId++;
				CollectionView.RegisterClassForCell(typeof(Cell), itemTypeId.ToString());
			}

			var cell = (Cell)CollectionView.DequeueReusableCell(itemTypeId.ToString(), indexPath);
			cell.Initialize(Element, itemType, item, index);

			// a semantically weak approach to OnAppearing; decided not to expose as such
			if (cell.OnBind == null)
				cell.OnBind += o => OnBind?.Invoke(o);

			return cell;
		}

		internal void ReloadData() => CollectionView.ReloadData();
		internal void ReloadItems(IEnumerable<int> positions)
		{
			var indices = positions.Select(o => NSIndexPath.FromRowSection(o, 0)).ToArray();
			CollectionView.ReloadItems(indices);
		}
		internal void DeleteItems(IEnumerable<int> positions)
		{
			var indices = positions.Select(o => NSIndexPath.FromRowSection(o, 0)).ToArray();
			CollectionView.DeleteItems(indices);
		}
		internal void MoveItem(int oldPosition, int newPosition)
		{
			base.MoveItem(
				CollectionView, 
				NSIndexPath.FromRowSection(oldPosition, 0), 
				NSIndexPath.FromRowSection(newPosition, 0)
			);
		}
		internal void ScrollToPosition(int position, bool animated = true)
		{
			CollectionView.ScrollToItem(
				indexPath: NSIndexPath.FromRowSection(position, 0), 
				scrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, 
				animated: animated
			);
		}
	}
}