美文网首页
swift替换系统方法

swift替换系统方法

作者: Th丶小伟 | 来源:发表于2023-06-12 11:05 被阅读0次
#import <Foundation/Foundation.h>

//! Project version number for SwiftyLoad.
FOUNDATION_EXPORT double SwiftyLoadVersionNumber;

//! Project version string for SwiftyLoad.
FOUNDATION_EXPORT const unsigned char SwiftyLoadVersionString[];


@protocol NSSwiftyLoadProtocol <NSObject>
@optional
+ (void)swiftyLoad;
+ (void)swiftyInitialize;
@end

#define SWIFTY_LOAD_INITIALIZE(className) \
@interface className(swizzle_swifty_hook)\
@end\
\
@implementation className(swizzle_swifty_hook)\
+ (void)load {if ([[self class] respondsToSelector:@selector(swiftyLoad)]) {[[self class] swiftyLoad];}}\
+ (void)initialize {if ([[self class] respondsToSelector:@selector(swiftyInitialize)]) {[[self class] swiftyInitialize];}}\
@end


extension UILabel : NSSwiftyLoadProtocol {
    
    public static func swiftyInitialize() {
        print("\(self)--->swiftyInitialize")
    }
    
    public static func swiftyLoad() {
        print("\(self)--->swiftyLoad")
        self.rtl_MethodSwizzling(fromMethod: #selector(setter: UILabel.textAlignment), toMethod: #selector(rtl_setTextAlignment(textAlignment:)))
    }
    
    @objc class func rtl_MethodSwizzling(fromMethod: Selector, toMethod: Selector) {
        guard let method1 = class_getInstanceMethod(self, fromMethod) else { return  }
        guard let method2 = class_getInstanceMethod(self, toMethod) else { return  }
        method_exchangeImplementations(method1, method2)
    }

    @objc func rtl_setTextAlignment(textAlignment: NSTextAlignment) {
        var alignment = textAlignment
        if UILabel.isRTL() {
            if textAlignment == .natural || textAlignment == .left {
                alignment = .right
            }else if textAlignment == .right {
                alignment = .left
            }
        }
        self.rtl_setTextAlignment(textAlignment: alignment)
    } 
}

相关文章

网友评论

      本文标题:swift替换系统方法

      本文链接:https://www.haomeiwen.com/subject/oeixeltx.html