Skip to content
This repository has been archived by the owner on May 1, 2024. It is now read-only.

Fix hangs and NREs with Entry Observer #14859

Merged
merged 2 commits into from
Nov 10, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 15 additions & 12 deletions Xamarin.Forms.Platform.iOS/Renderers/EntryRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ public abstract class EntryRendererBase<TControl> : ViewRenderer<Entry, TControl
bool _useLegacyColorManagement;

bool _disposed;
bool _observedSublayers;
IDisposable _selectedTextRangeObserver;
IDisposable _clearButtonSublayerObserver;
bool _nativeSelectionIsUpdating;

bool _cursorPositionChangePending;
Expand Down Expand Up @@ -93,7 +93,12 @@ protected override void Dispose(bool disposing)
Control.EditingDidEnd -= OnEditingEnded;
Control.ShouldChangeCharacters -= ShouldChangeCharacters;
_selectedTextRangeObserver?.Dispose();
_clearButtonSublayerObserver?.Dispose();

if (_observedSublayers)
{
ClearButton?.Layer?.RemoveObserver(this, new NSString("sublayers"));
_observedSublayers = false;
}
}
}

Expand Down Expand Up @@ -128,7 +133,8 @@ protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
textField.ShouldChangeCharacters += ShouldChangeCharacters;
_selectedTextRangeObserver = textField.AddObserver("selectedTextRange", NSKeyValueObservingOptions.New, UpdateCursorFromControl);

_clearButtonSublayerObserver = ClearButton?.Layer.AddObserver(new NSString("sublayers"), NSKeyValueObservingOptions.New, UpdateClearButtonSublayer);
ClearButton?.Layer.AddObserver(this, new NSString("sublayers"), NSKeyValueObservingOptions.New, IntPtr.Zero);
_observedSublayers = true;
}

// When we set the control text, it triggers the UpdateCursorFromControl event, which updates CursorPosition and SelectionLength;
Expand Down Expand Up @@ -160,6 +166,12 @@ protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
UpdateClearButtonVisibility();
}

public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
{
if (keyPath == new NSString("sublayers") && _defaultClearImage == null)
UpdateClearButtonVisibility();
}

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == Entry.PlaceholderProperty.PropertyName || e.PropertyName == Entry.PlaceholderColorProperty.PropertyName)
Expand Down Expand Up @@ -434,15 +446,6 @@ void UpdateCursorFromControl(NSObservedChange obj)
}
}

void UpdateClearButtonSublayer(NSObservedChange obj)
{
if (Control == null || Element == null)
return;

if (_defaultClearImage == null)
UpdateClearButtonVisibility();
}

void UpdateCursorSelection()
{
if (_nativeSelectionIsUpdating || Control == null || Element == null)
Expand Down