-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
ViewExtensions.cs
529 lines (435 loc) · 15.1 KB
/
ViewExtensions.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
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading.Tasks;
using CoreGraphics;
using Foundation;
using Microsoft.Maui.Devices;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Media;
using ObjCRuntime;
using UIKit;
using static Microsoft.Maui.Primitives.Dimension;
namespace Microsoft.Maui.Platform
{
public static partial class ViewExtensions
{
internal const string BackgroundLayerName = "MauiBackgroundLayer";
public static void UpdateIsEnabled(this UIView platformView, IView view)
{
if (platformView is not UIControl uiControl)
return;
uiControl.Enabled = view.IsEnabled;
}
public static void Focus(this UIView platformView, FocusRequest request)
{
platformView.BecomeFirstResponder();
}
public static void Unfocus(this UIView platformView, IView view)
{
platformView.ResignFirstResponder();
}
public static void UpdateVisibility(this UIView platformView, IView view) =>
ViewExtensions.UpdateVisibility(platformView, view.Visibility);
public static void UpdateVisibility(this UIView platformView, Visibility visibility)
{
switch (visibility)
{
case Visibility.Visible:
platformView.Inflate();
platformView.Hidden = false;
break;
case Visibility.Hidden:
platformView.Inflate();
platformView.Hidden = true;
break;
case Visibility.Collapsed:
platformView.Hidden = true;
platformView.Collapse();
break;
}
}
public static void UpdateBackground(this ContentView platformView, IBorderStroke border)
{
bool hasBorder = border.Shape != null && border.Stroke != null;
if (hasBorder)
{
platformView.UpdateMauiCALayer(border);
}
}
public static void UpdateBackground(this UIView platformView, IView view) =>
platformView.UpdateBackground(view.Background);
public static void UpdateBackground(this UIView platformView, Paint? paint)
{
// Remove previous background gradient layer if any
platformView.RemoveBackgroundLayer();
if (paint.IsNullOrEmpty())
return;
if (paint is SolidPaint solidPaint)
{
Color backgroundColor = solidPaint.Color;
if (backgroundColor == null)
platformView.BackgroundColor = ColorExtensions.BackgroundColor;
else
platformView.BackgroundColor = backgroundColor.ToPlatform();
return;
}
else if (paint is GradientPaint gradientPaint)
{
var backgroundLayer = gradientPaint?.ToCALayer(platformView.Bounds);
if (backgroundLayer != null)
{
backgroundLayer.Name = BackgroundLayerName;
platformView.BackgroundColor = UIColor.Clear;
platformView.InsertBackgroundLayer(backgroundLayer, 0);
}
}
}
public static void UpdateFlowDirection(this UIView platformView, IView view)
{
UISemanticContentAttribute updateValue = platformView.SemanticContentAttribute;
switch (view.FlowDirection)
{
case FlowDirection.MatchParent:
updateValue = UISemanticContentAttribute.Unspecified;
break;
case FlowDirection.LeftToRight:
updateValue = UISemanticContentAttribute.ForceLeftToRight;
break;
case FlowDirection.RightToLeft:
updateValue = UISemanticContentAttribute.ForceRightToLeft;
break;
}
if (updateValue != platformView.SemanticContentAttribute)
platformView.SemanticContentAttribute = updateValue;
}
public static void UpdateOpacity(this UIView platformView, IView view)
{
platformView.Alpha = (float)view.Opacity;
}
public static void UpdateAutomationId(this UIView platformView, IView view) =>
platformView.AccessibilityIdentifier = view.AutomationId;
public static void UpdateClip(this UIView platformView, IView view)
{
if (platformView is WrapperView wrapper)
wrapper.Clip = view.Clip;
}
public static void UpdateShadow(this UIView platformView, IView view)
{
var shadow = view.Shadow;
var clip = view.Clip;
// If there is a clip shape, then the shadow should be applied to the clip layer, not the view layer
if (clip == null)
{
if (shadow == null)
platformView.ClearShadow();
else
platformView.SetShadow(shadow);
}
else
{
if (platformView is WrapperView wrapperView)
wrapperView.Shadow = view.Shadow;
}
}
public static void UpdateBorder(this UIView platformView, IView view)
{
var border = (view as IBorder)?.Border;
if (platformView is WrapperView wrapperView)
wrapperView.Border = border;
}
public static T? FindDescendantView<T>(this UIView view) where T : UIView
{
var queue = new Queue<UIView>();
queue.Enqueue(view);
while (queue.Count > 0)
{
var descendantView = queue.Dequeue();
if (descendantView is T result)
return result;
for (var i = 0; i < descendantView.Subviews?.Length; i++)
queue.Enqueue(descendantView.Subviews[i]);
}
return null;
}
public static void UpdateBackgroundLayerFrame(this UIView view)
{
if (view == null || view.Frame.IsEmpty)
return;
var layer = view.Layer;
if (layer == null || layer.Sublayers == null || layer.Sublayers.Length == 0)
return;
foreach (var sublayer in layer.Sublayers)
{
if (sublayer.Name == BackgroundLayerName && sublayer.Frame != view.Bounds)
{
sublayer.Frame = view.Bounds;
break;
}
}
}
public static void InvalidateMeasure(this UIView platformView, IView view)
{
platformView.SetNeedsLayout();
platformView.Superview?.SetNeedsLayout();
}
public static void UpdateWidth(this UIView platformView, IView view)
{
UpdateFrame(platformView, view);
}
public static void UpdateHeight(this UIView platformView, IView view)
{
UpdateFrame(platformView, view);
}
public static void UpdateMinimumHeight(this UIView platformView, IView view)
{
UpdateFrame(platformView, view);
}
public static void UpdateMaximumHeight(this UIView platformView, IView view)
{
UpdateFrame(platformView, view);
}
public static void UpdateMinimumWidth(this UIView platformView, IView view)
{
UpdateFrame(platformView, view);
}
public static void UpdateMaximumWidth(this UIView platformView, IView view)
{
UpdateFrame(platformView, view);
}
public static void UpdateFrame(UIView platformView, IView view)
{
if (!IsExplicitSet(view.Width) || !IsExplicitSet(view.Height))
{
// Ignore the initial setting of the value; the initial layout will take care of it
return;
}
// Updating the frame (assuming it's an actual change) will kick off a layout update
// Handling of the default width/height will be taken care of by GetDesiredSize
var currentFrame = platformView.Frame;
platformView.Frame = new CoreGraphics.CGRect(currentFrame.X, currentFrame.Y, view.Width, view.Height);
}
public static async Task UpdateBackgroundImageSourceAsync(this UIView platformView, IImageSource? imageSource, IImageSourceServiceProvider? provider)
{
if (provider == null)
return;
if (imageSource != null)
{
var service = provider.GetRequiredImageSourceService(imageSource);
var result = await service.GetImageAsync(imageSource);
var backgroundImage = result?.Value;
if (backgroundImage == null)
return;
platformView.BackgroundColor = UIColor.FromPatternImage(backgroundImage);
}
}
public static int IndexOfSubview(this UIView platformView, UIView subview)
{
if (platformView.Subviews.Length == 0)
return -1;
return Array.IndexOf(platformView.Subviews, subview);
}
public static UIImage? ConvertToImage(this UIView view)
{
var imageRenderer = new UIGraphicsImageRenderer(view.Bounds.Size);
return imageRenderer.CreateImage((a) =>
{
view.Layer.RenderInContext(a.CGContext);
});
}
public static UINavigationController? GetNavigationController(this UIView view)
{
var rootController = view.Window?.RootViewController;
if (rootController is UINavigationController nc)
return nc;
return rootController?.NavigationController;
}
internal static void Collapse(this UIView view)
{
// See if this view already has a collapse constraint we can use
foreach (var constraint in view.Constraints)
{
if (constraint is CollapseConstraint collapseConstraint)
{
// Active the collapse constraint; that will squish the view down to zero height
collapseConstraint.Active = true;
return;
}
}
// Set up a collapse constraint and turn it on
var collapse = new CollapseConstraint();
view.AddConstraint(collapse);
collapse.Active = true;
}
internal static bool Inflate(this UIView view)
{
// Find and deactivate the collapse constraint, if any; the view will go back to its normal height
foreach (var constraint in view.Constraints)
{
if (constraint is CollapseConstraint collapseConstraint)
{
collapseConstraint.Active = false;
return true;
}
}
return false;
}
public static void ClearSubviews(this UIView view)
{
for (int n = view.Subviews.Length - 1; n >= 0; n--)
{
view.Subviews[n].RemoveFromSuperview();
}
}
internal static Rect GetPlatformViewBounds(this IView view)
{
var platformView = view?.ToPlatform();
if (platformView == null)
{
return new Rect();
}
return platformView.GetPlatformViewBounds();
}
internal static Rect GetPlatformViewBounds(this UIView platformView)
{
if (platformView == null)
return new Rect();
var superview = platformView;
while (superview.Superview is not null)
{
superview = superview.Superview;
}
var convertPoint = platformView.ConvertRectToView(platformView.Bounds, superview);
var X = convertPoint.X;
var Y = convertPoint.Y;
var Width = convertPoint.Width;
var Height = convertPoint.Height;
return new Rect(X, Y, Width, Height);
}
internal static Matrix4x4 GetViewTransform(this IView view)
{
var platformView = view?.ToPlatform();
if (platformView == null)
return new Matrix4x4();
return platformView.Layer.GetViewTransform();
}
internal static Matrix4x4 GetViewTransform(this UIView view)
=> view.Layer.GetViewTransform();
internal static Graphics.Rect GetBoundingBox(this IView view)
=> view.ToPlatform().GetBoundingBox();
internal static Graphics.Rect GetBoundingBox(this UIView? platformView)
{
if (platformView == null)
return new Rect();
var nvb = platformView.GetPlatformViewBounds();
var transform = platformView.GetViewTransform();
var radians = transform.ExtractAngleInRadians();
var rotation = CoreGraphics.CGAffineTransform.MakeRotation((nfloat)radians);
CGAffineTransform.CGRectApplyAffineTransform(nvb, rotation);
return new Rect(nvb.X, nvb.Y, nvb.Width, nvb.Height);
}
internal static UIView? GetParent(this UIView? view)
{
return view?.Superview;
}
internal static void LayoutToSize(this IView view, double width, double height)
{
var platformFrame = new CGRect(0, 0, width, height);
if (view.Handler is IPlatformViewHandler viewHandler && viewHandler.PlatformView != null)
viewHandler.PlatformView.Frame = platformFrame;
view.Arrange(platformFrame.ToRectangle());
}
internal static Size LayoutToMeasuredSize(this IView view, double width, double height)
{
var size = view.Measure(width, height);
var platformFrame = new CGRect(0, 0, size.Width, size.Height);
if (view.Handler is IPlatformViewHandler viewHandler && viewHandler.PlatformView != null)
viewHandler.PlatformView.Frame = platformFrame;
view.Arrange(platformFrame.ToRectangle());
return size;
}
public static void UpdateInputTransparent(this UIView platformView, IViewHandler handler, IView view)
{
if (view is ITextInput textInput)
{
platformView.UpdateInputTransparent(textInput.IsReadOnly, view.InputTransparent);
return;
}
platformView.UserInteractionEnabled = !view.InputTransparent;
}
public static void UpdateInputTransparent(this UIView platformView, bool isReadOnly, bool inputTransparent)
{
platformView.UserInteractionEnabled = !(isReadOnly || inputTransparent);
}
internal static IWindow? GetHostedWindow(this IView? view)
=> GetHostedWindow(view?.Handler?.PlatformView as UIView);
internal static IWindow? GetHostedWindow(this UIView? view)
=> GetHostedWindow(view?.Window);
internal static bool IsLoaded(this UIView uiView) =>
uiView.Window != null;
internal static IDisposable OnLoaded(this UIView uiView, Action action)
{
if (uiView.IsLoaded())
{
action();
return new ActionDisposable(() => { });
}
Dictionary<NSString, NSObject> observers = new Dictionary<NSString, NSObject>();
ActionDisposable? disposable = new ActionDisposable(() =>
{
foreach (var thing in observers)
uiView.Layer.RemoveObserver(thing.Value, thing.Key);
});
// Ideally we could wire into UIView.MovedToWindow but there's no way to do that without just inheriting from every single
// UIView. So we just make our best attempt by observering some properties that are going to fire once UIView is attached to a window.
observers.Add(new NSString("bounds"), (NSObject)uiView.Layer.AddObserver("bounds", Foundation.NSKeyValueObservingOptions.OldNew, (_) => OnLoadedCheck()));
observers.Add(new NSString("frame"), (NSObject)uiView.Layer.AddObserver("frame", Foundation.NSKeyValueObservingOptions.OldNew, (_) => OnLoadedCheck()));
// OnLoaded is called at the point in time where the xplat view knows it's going to be attached to the window.
// So this just serves as a way to queue a call on the UI Thread to see if that's enough time for the window
// to get attached.
uiView.BeginInvokeOnMainThread(OnLoadedCheck);
void OnLoadedCheck()
{
if (uiView.IsLoaded() && disposable != null)
{
disposable.Dispose();
disposable = null;
action();
}
};
return disposable;
}
internal static IDisposable OnUnloaded(this UIView uiView, Action action)
{
if (!uiView.IsLoaded())
{
action();
return new ActionDisposable(() => { });
}
Dictionary<NSString, NSObject> observers = new Dictionary<NSString, NSObject>();
ActionDisposable? disposable = new ActionDisposable(() =>
{
foreach (var thing in observers)
uiView.Layer.RemoveObserver(thing.Value, thing.Key);
});
// Ideally we could wire into UIView.MovedToWindow but there's no way to do that without just inheriting from every single
// UIView. So we just make our best attempt by observering some properties that are going to fire once UIView is attached to a window.
observers.Add(new NSString("bounds"), (NSObject)uiView.Layer.AddObserver("bounds", Foundation.NSKeyValueObservingOptions.OldNew, (_) => UnLoadedCheck()));
observers.Add(new NSString("frame"), (NSObject)uiView.Layer.AddObserver("frame", Foundation.NSKeyValueObservingOptions.OldNew, (_) => UnLoadedCheck()));
// OnUnloaded is called at the point in time where the xplat view knows it's going to be detached from the window.
// So this just serves as a way to queue a call on the UI Thread to see if that's enough time for the window
// to get detached.
uiView.BeginInvokeOnMainThread(UnLoadedCheck);
void UnLoadedCheck()
{
if (!uiView.IsLoaded() && disposable != null)
{
disposable.Dispose();
disposable = null;
action();
}
};
return disposable;
}
}
}