iOS开发者进阶

iOS 15适配UITableView,一个分类搞定

2021-12-02  本文已影响0人  __Mr_Xie__
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UITableView (fit)

@end

NS_ASSUME_NONNULL_END
#import "UITableView+fit.h"
#import <objc/message.h>

@implementation UITableView (fit)


+ (void)load{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self exchangeInstance:[self class] selector:@selector(initWithFrame:style:) withSwizzledSelector:@selector(ev_initWithFrame:style:)];
    });
    
}

- (instancetype)ev_initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    
    UITableView *tableView = [self ev_initWithFrame:frame style:style];
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_14_5
    if (@available(iOS 15.0, *)) {
        tableView.sectionHeaderTopPadding = 0;
    }
#endif
    return tableView;
    
}

+ (BOOL)exchangeInstance:(Class)class selector:(SEL)originalSelector withSwizzledSelector: (SEL)swizzledSelector{
    
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    if(!originalMethod || !swizzledMethod){
        
        return NO;
    }
    // 若已经存在,则添加会失败
    BOOL didAddMethod = class_addMethod(class,
                                        originalSelector,
                                        method_getImplementation(swizzledMethod),
                                        method_getTypeEncoding(swizzledMethod));
    
    // 若原来的方法并不存在,则添加即可
    if (didAddMethod) {
        class_replaceMethod(class,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
    
    return YES;
}

@end
上一篇 下一篇

猜你喜欢

热点阅读