Xamarin.iOS中AddObserver监听UIView.Window变更事件无响应排查
在Xamarin.Forms中实现生命周期效果的iOS端问题
我正尝试在Xamarin.Forms中实现生命周期效果,但iOS版本遇到了问题:无法监听UIView.Window的变更通知事件。我的需求是在视图能够向上导航至根父级时再触发事件,已知Xamarin.Community Toolkit有类似效果,但它的触发时机过早,不符合需求。
现有实现代码
public class CustomLifeCycleEffectRouter : PlatformEffect { private const NSKeyValueObservingOptions ObservingOptions = NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New; UIView? _nativeView; CustomLifeCycleEffect? _lifeCycleEffect; IDisposable _isLoadedObserverDisposable; protected override void OnAttached() { _lifeCycleEffect = Element.Effects.OfType<CustomLifeCycleEffect>().FirstOrDefault() ?? throw new ArgumentNullException($"The effect {nameof(CustomLifeCycleEffect)} can't be null."); _nativeView = Control ?? Container; _isLoadedObserverDisposable = _nativeView?.AddObserver("window", ObservingOptions, isWindowAttachedObserver); } protected override void OnDetached() { _lifeCycleEffect?.RaiseUnloadedEvent(Element); _isLoadedObserverDisposable.Dispose(); } private void isWindowAttachedObserver(NSObservedChange nsObservedChange) { if (_nativeView.Window != null) _lifeCycleEffect?.RaiseLoadedEvent(Element); else _lifeCycleEffect?.RaiseUnloadedEvent(Element); } }
补充细节
我已创建示例项目复现该问题,目标是让调试输出仅保留以下正常信息:
$"{elementName} is already a page."
$"{elementName} is a child of {pageName}."
需要避免出现以下错误信息(这些信息位于ViewExtensions类中):
$"{elementName} does not have a parent ???."
$"How can {elementName} be loaded and not have a parent in hierarchy ???."
$"WTF??? we never loaded {elementName}."
另外,我也尝试过Xamarin Community Toolkit路由效果的变体,它基本可用,但在视图为模板化时会提前触发loaded事件(此时视图还未拥有父级),这正是我最初弃用它的原因,若能解决该边缘情况,我也可以使用该版本。
内容的提问来源于stack exchange,提问作者Sonic1015
相关产品推荐
相关产品推荐

