Swizzling 方法交换

TableView 默认空页面制作

// UITableView+ex.h
#import <UIKit/UIKit.h>
#import <objc/runtime.h>

@interface UITableView (ex)

@property(strong, nonatomic)UIView *lgValue;

@end
// UITableView+ex.m
#import "UITableView+ex.h"

#define LGDefaultView "LGDefaultView"

@implementation UITableView (ex)
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method originMethod = class_getInstanceMethod(self, @selector(reloadData));
        Method currentMethod = class_getInstanceMethod(self, @selector(lg_reloadData));
        method_exchangeImplementations(originMethod, currentMethod);
    });
}

- (void)lg_reloadData {
    // 调用系统的 reloadData
    [self lg_reloadData];
}

- (void)fullDefaultView {
    id<UITableViewDataSource> dataSource = self.dataSource;
    NSInteger section = [dataSource respondsToSelector:@selector(numberOfSectionsInTableView:)] ? [dataSource numberOfSectionsInTableView:self] : 1;
    NSInteger rows = 0;
    for (NSInteger i = 0; i < section; i++) {
        rows += [dataSource tableView:self numberOfRowsInSection:i];
    }

    if (!rows) {
        self.lgValue = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 55, 55)];
        self.lgValue.backgroundColor = [UIColor redColor];
        [self addSubview:self.lgValue];
    } else {
        [self.lgValue removeFromSuperview];
    }
}

#pragma mark -- GETTE AND SETTER
- (void)setLgValue:(UIView *)lgValue {
    objc_setAssociatedObject(self, LGDefaultView, lgValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIView *)getLgValue {
    return objc_getAssociatedObject(self, LGDefaultView);
}

@end

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐