gpt4 book ai didi

c# - 从子控件检测 ViewDidUnload

转载 作者:行者123 更新时间:2023-11-29 02:57:37 26 4
gpt4 key购买 nike

我试图弄清楚如何挂接到控件的 super View 上的ViewDidUnload。为了说明我为什么需要这个,请考虑我的 ControlFactory 类,它生成 UIButton(以及其他控件):

internal static class ControlFactory
{
private static readonly IObservable<Unit> sharedDynamicTypeChanged = TinyIoCContainer.Current
.Resolve<ISystemNotificationsService>()
.DynamicTypeChanged
.Publish()
.RefCount();

public static UIButton CreateButton()
{
return new DynamicTypeAwareButton(sharedDynamicTypeChanged, UIFont.PreferredHeadline);
}
}

这里的想法是,工厂生产的每个 UIButton 都会根据用户的动态类型设置自动缩放其字体。我的 DynamicTypeAwareButton 是一个内部类,如下所示:

private sealed class DynamicTypeAwareButton : UIButton
{
private readonly IObservable<Unit> dynamicTypeChanged;
private readonly UIFont font;
private IDisposable subscription;

public DynamicTypeAwareButton(IObservable<Unit> dynamicTypeChanged, UIFont font)
{
this.dynamicTypeChanged = dynamicTypeChanged;
this.font = font;
}

public override void MovedToSuperview()
{
base.MovedToSuperview();

// TODO: figure out when to subscribe/unsubscribe
this.subscription = this.dynamicTypeChanged
.StartWith(Unit.Default)
.Subscribe(_ => this.UpdateFont());
}

private void UpdateFont()
{
this.Font = this.font;
}
}

如评论中所述,问题是我需要知道按钮的 super View 何时卸载,以便我可以处理订阅。我可以轻松访问 super View ,但我找不到任何在卸载该 super View 时收到通知的 Hook 。

有谁知道有什么方法可以实现这一目标吗?

最佳答案

而不是 MovedToSuperView 使用 WillMoveToSuperView - 它会被调用两次,一次是在按钮被添加到 View 时(即 => 订阅),一次是在按钮被添加到 View 时即将被丢弃(其中 newSuperview 将为空)。

此外,您可以使用 SerialDisposable 更优雅地编写它:

private sealed class DynamicTypeAwareButton : UIButton
{
private readonly IObservable<Unit> dynamicTypeChanged;
private readonly UIFont font;
private SerialDisposable subscription = new SerialDisposable();

public override void WillMoveToSuperView(UIView newView)
{
base.WillMoveToSuperView();

// Whenever SerialDisposable.Disposable is assigned, it throws
// away the previous one. That means, even if the Button gets
// moved to a new non-null View, we're still not leaking a
// subscription
if (newView != null)
{
this.subscription.Disposable = this.dynamicTypeChanged
.StartWith(Unit.Default)
.Subscribe(_ => this.UpdateFont());
}
else
{
this.subscription.Disposable = Disposable.Empty;
}
}

public void UpdateFont()
{
/* ... */
}
}

关于c# - 从子控件检测 ViewDidUnload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23712351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com