UIView 的方法调整 [英] Method Swizzling for UIView

查看:22
本文介绍了UIView 的方法调整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注这个"指导.捕获 UIView touchesBegan,但是当我 NSLog() touchesBegan 在它用于的 UIViewController 中时,它不会触发,但会触发混合的方法.有没有办法让它在两者中都着火?

I am following "This" guide. to capture UIView touchesBegan, but when I NSLog() touchesBegan in the UIViewController that this is for, it doesn't fire but does fire in the swizzled method. Is there a way I can have it fire in both?

推荐答案

当 swizzling 方法时,你基本上是在告诉 Objective-C 运行时改变它的方法 selector 的内部映射(你如何调用它)到一个方法实现(它在调用时做什么).要意识到的关键是这些在 Objective-C 中实际上不是一回事(尽管我们在编码时通常不会考虑这种区别).如果你能理解选择器映射的概念,那么理解 swizzling 就很容易了.

When swizzling methods, you are basically telling the Objective-C runtime to change its internal mapping of a method selector (how you call it) to a method implementation (what it does when called). The key thing to realize is that these are actually not the same thing in Objective-C (though we usually don't think about this distinction when coding). If you can understand the concept of selector mapping, understanding swizzling is easy.

典型的模式是通过交换它们的选择器,将现有方法(通常是您无法控制的类)与您自己的相同签名的自定义方法交换,以便您的选择器指向现有实现和现有选择器点到您的实施.

The typical pattern is to swap an existing method (usually of a class you don't control) with your own custom method of the same signature by exchanging their selectors so that your selector points to the existing implementation and the existing selector points to your implementation.

完成此操作后,您实际上可以通过调用自定义方法的选择器来调用原始实现.

Having done this, you can actually call the original implementation by calling your custom method's selector.

对于外部观察者来说,这似乎创建了一个重入循环:

To an outside observer this appears to create a re-entrancy loop:

- (void)swizzled_touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // custom logic

    [self swizzled_touchesBegan:touches withEvent:event]; // <-- this actually calls the original implementation

    // custom logic
}

...但是因为你交换了选择器,看起来递归的选择器实际上指向了原来的实现.这就是为什么调用 [view touchesBegan: withEvent:] 最终会首先调用你的 swizzled 方法.

…but because you have swapped the selectors, the selector that appears to recurse actually points to the original implementation. This is exactly why calling [view touchesBegan: withEvent:] ends up calling your swizzled method in the first place.

整洁吧?

这篇关于UIView 的方法调整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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