没有子类化 UIView 或 UIViewController:是否可以捕获是否添加了子视图? [英] Without subclassing a UIView or UIViewController: possible to catch if a subview was added?

查看:65
本文介绍了没有子类化 UIView 或 UIViewController:是否可以捕获是否添加了子视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果将视图作为子视图添加到控制器的现有视图中,是否可以捕获事件或通知?我在这里有一个库,我不能子类化,但需要知道是否添加了特定的子视图来触发自定义操作.有机会吗?

Is there a way to catch an event or notification if a view was added as subview to an existing view of a controller? I have a library here and I cannot subclass but need to know if a specific subview was added to trigger a custom action. Is there a chance?

推荐答案

并不是说我认为这种方法比 @tiguero 建议的方法更干净,但我认为它稍微安全一些(看看为什么在我的评论中使用类别可能会很危险)他的回答)并为您提供更大的灵活性.

Not that I think this method is cleaner than the one @tiguero suggested, but I think it's slightly safer (see why using categories could be dangerous in my comments to his answer) and offers you more flexibilty.

这在某种程度上,虽然不完全是,但更多是在概念层面上,与 KVO 的工作方式相同.您基本上动态地更改 willMoveToSuperview 的实现并将您的通知代码添加到其中.

This is somehow, although not exactly, but more at the conceptual level, the same way KVO works. You basically, dynamically alter the implementation of willMoveToSuperview and add your notification code to it.

//Makes views announce their change of superviews
Method method = class_getInstanceMethod([UIView class], @selector(willMoveToSuperview:));
IMP originalImp = method_getImplementation(method);

void (^block)(id, UIView*) = ^(id _self, UIView* superview) {
    [_self willChangeValueForKey:@"superview"];
    originalImp(_self, @selector(willMoveToSuperview:), superview);
    [_self didChangeValueForKey:@"superview"];
};

IMP newImp = imp_implementationWithBlock((__bridge void*)block);
method_setImplementation(method, newImp);

这篇关于没有子类化 UIView 或 UIViewController:是否可以捕获是否添加了子视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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