简体   繁体   English

我怎样才能调配 UIView.init

[英]How can I swizzle UIView.init

I'm attempting to swizzle the init methods of UIView and anything that subclasses it.我正在尝试调整 UIView 的 init 方法以及任何它的子类。 Thus far my attempts only lead to crashes or simply do nothing noticeable.到目前为止,我的尝试只会导致崩溃或根本没有做任何明显的事情。

The outcome in trying to achieve is being able to override the value of the views border colour and width in an attempt to visualise view frames without needing a debugger attached.尝试实现的结果是能够覆盖视图边框颜色和宽度的值,以尝试在不需要附加调试器的情况下可视化视图框架。

I've never tried swizzling before but fancied trying this out - a quick google found this article that explains how to do it with an extension .我以前从未尝试过 swizzling,但很想尝试一下 - 一个快速的谷歌发现这篇文章解释了如何使用extension来做到这一点。

extension UIView {
    
    static let classInit: Void = {
        guard let originalMethod = class_getInstanceMethod(
            UIView.self,
            #selector(layoutSubviews)
        ), let swizzledMethod = class_getInstanceMethod(
            UIView.self,
            #selector(swizzled_layoutSubviews)
        ) else {
            return
        }
       method_exchangeImplementations(originalMethod, swizzledMethod)
    }()

    @objc func swizzled_layoutSubviews() {
        swizzled_layoutSubviews()
        self.layer.borderColor = UIColor.red.cgColor
        self.layer.borderWidth = 2
    }

}

Then you just need to make sure you run the swizzle in your AppDelegate didFinishLaunchingWithOptions method or somewhere at the start of your app然后,您只需要确保在 AppDelegate didFinishLaunchingWithOptions方法中或在应用程序开始的某个地方运行 swizzle

UIView.classInit

在此处输入图像描述

The above code works for me on an iOS 13.7 simulator, tho from what I have read you really should not be trying to override methods like this especially from such a core object, it'd be safer to subclass UIView if possible.上面的代码适用于我在 iOS 13.7 模拟器上,但从我读过的内容来看,你真的不应该尝试覆盖这样的方法,特别是从这样的核心 object,如果可能的话,子类UIView会更安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM