我试图弄清楚如何在控件的superview上连接到ViewDidUnload。为了说明我为什么需要这样做,请考虑我的ControlFactory类,它生成UIButtons (以及其他控件):
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;
}
}正如注释中所指出的,问题在于,我需要知道按钮的superview何时被卸载,这样我就可以释放订阅。我可以很容易地访问superview,但是在卸载superview时,我找不到需要通知的钩子。
有人知道有什么办法可以做到这一点吗?
发布于 2014-05-18 02:58:21
而不是MovedToSuperView使用WillMoveToSuperView -它将被调用两次,一次是当Button被添加到视图中时(即=>订阅),另一次是当Button即将被销毁时(其中newSuperview将为null)。
此外,您还可以使用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()
{
/* ... */
}
}https://stackoverflow.com/questions/23712351
复制相似问题