首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从子控件检测ViewDidUnload

从子控件检测ViewDidUnload
EN

Stack Overflow用户
提问于 2014-05-17 14:18:21
回答 1查看 72关注 0票数 0

我试图弄清楚如何在控件的superview上连接到ViewDidUnload。为了说明我为什么需要这样做,请考虑我的ControlFactory类,它生成UIButtons (以及其他控件):

代码语言:javascript
复制
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是一个内部类,如下所示:

代码语言:javascript
复制
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时,我找不到需要通知的钩子。

有人知道有什么办法可以做到这一点吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-18 02:58:21

而不是MovedToSuperView使用WillMoveToSuperView -它将被调用两次,一次是当Button被添加到视图中时(即=>订阅),另一次是当Button即将被销毁时(其中newSuperview将为null)。

此外,您还可以使用SerialDisposable编写更优雅的代码。

代码语言:javascript
复制
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()
    {
        /* ... */
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23712351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档