IOS,UIView,检测子视图中的隐藏状态变化 [英] IOS, UIView, Detect Hidden State Change in Subview

查看:964
本文介绍了IOS,UIView,检测子视图中的隐藏状态变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何都要在UIView(不是UIViewController)的子视图中检测隐藏状态更改(或其他更改)。想以某种方式检测到这种异步。

Is there anyway to detect a hidden state change (or other change) in a sub view in a UIView (not UIViewController). Would like to detect this async somehow.

我有疯狂的理由。

推荐答案

您可以使用KVO(键值观察)来检测属性值的变化隐藏

You can use KVO (key value observing) to detect a change to the value of the property hidden.

以下列方式添加您的观察者(在此示例中为 self ):

Add your observer (self in this example) in the following way:

UIView* viewToObserve = [self getViewToObserve];  // implement getViewToObserve
[viewToObserve addObserver:self forKeyPath:@"hidden" options:0 context:NULL];

现在将以下方法添加到您的观察者类:

Now add the following method to your observer class:

- (void) observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
{
  UIView* viewToObserve = [self getViewToObserve];
  if (object == viewToObserve)
  {
    if ([keyPath isEqualToString:@"hidden"])
    {
      // react to state change
    }
  }
}

每当<时,将调用观察者方法code>隐藏属性更改其值。如果我没有弄错的话,将在进行属性更改的线程的上下文中同步调用该方法。如果您需要异步通知,可以自己添加,例如使用 NSObject 方法之一 performSelector:withObject:afterDelay: performSelector:onThread:withObject:waitUntilDone:

The observer method will be invoked whenever the hiddenproperty changes its value. If I am not mistaken, the method will be invoked synchronously in the context of the thread that makes the change to the property. If you need asynchronous notification you can add that yourself, for instance by using one of the NSObject methods performSelector:withObject:afterDelay: or performSelector:onThread:withObject:waitUntilDone:.

BTW:你不需要支票显然,观察者方法,如果您只观察单个对象和/或属性。为了便于说明,我把支票留了下来。我还建议您阅读有关 KVO KVC (键值编码),以了解这里发生了什么。

BTW: You don't need the checks in the observer method, obviously, if you only observe a single object and/or property. I left the checks in for illustration purposes. I also recommend reading Apple's documentation on KVO and KVC (key value coding) to understand what's going on here.

即使观察者被解除分配,运行时也会继续通知您的观察者 - 导致应用程序崩溃!因此,不要忘记在取消分配之前移除观察者,最迟这应该发生在观察者的 dealloc

The runtime happily continues notifying your observer even if the observer is deallocated - resulting in an application crash! So don't forget to remove the observer before it is de-allocated, at the latest this should happen in the observer's dealloc:

- (void) dealloc
{
    UIView* viewToObserve = [self getViewToObserve];
    [viewToObserve removeObserver:self forKeyPath:@"hidden"];
    [super dealloc];
}

这篇关于IOS,UIView,检测子视图中的隐藏状态变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆