iOS 15適配UITableView,一個分類搞定

#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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章