疑问?
在开发中我们经常需要用到的组件,自然就是错误页了。一般而言,对于网络错误,数据为空等状态,我们都会在当前的页面中展示一张错误页来提示用户,类似这样:
常用写法
要实现这个需求其实并不难,大概分为以下几种。
- 直接生成
1. 自定义一个错误页的,就像这样:
#import
typedef NS_ENUM(NSUInteger, HPErrorType) {
HPErrorTypeUnavailableNetwork,
HPErrorTypeEmptyData,
HPErrorTypeDefault = HPErrorTypeUnavailableNetwork
};
@interface HPErrorView : UIView
/**
当前错误类型【默认为Default】
*/
@property (nonatomic, assign) HPErrorType errorType;
/**
要显示的文案【为nil使用默认文案】
*/
@property (nonatomic, copy) NSString *customText;
/**
实例化
*/
+(instancetype)viewWithType:(HPErrorType)type;
@end
2. 然后在需要的页面中直接控制添加和移除:
2.1. 显示
#import "HPErrorView.h"
static const NSUInteger kErrorViewTag = 1024;
...
@implementation ViewController
/**
显示错误页
*/
- (void)directShowErrorView {
dispatch_main_async_safe(^{
HPErrorView *errorView = [self checkErrorViewExist];
if (!errorView) {
errorView = [HPErrorView viewWithType:HPErrorTypeDefault]; // 创建
errorView.tag = kErrorViewTag;
[self.view addSubview:errorView]; // 添加
// 布局
errorView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:errorView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:errorView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1.0f constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:errorView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:errorView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0]];
}
[self.view bringSubviewToFront:errorView];
});
}
@end
2.2. 移除
/**
移除错误页
*/
- (void)directShowErrorView {
dispatch_main_async_safe(^{
HPErrorView *errorView = [self checkErrorViewExist]; // 检查是否存在
if (errorView) {
[errorView removeFromSuperview]; // 移除
}
});
}
2.3. 检测是否存在
/**
检测当前页面是否存在ErrorView
@return ErrorView
*/
- (HPErrorView *)checkErrorViewExist {
return [self.view viewWithTag:kErrorViewTag];
}
2.4. 方法调用
- (void)changErrorViewStatus:(id)sender {
if ([self.item.title isEqualToString:@"展示"]) {
self.item.title = @"隐藏";
// 1. 直接显示
[self directShowErrorView];
} else {
self.item.title = @"展示";
// 1. 直接隐藏
[self directRemoveErrorView];
}
}
- 使用分类控制
使用分类进行控制的原理其实跟“直接调用”方式是差不多的,只是将这部分代码放入分类中实现代码复用。代码结构如下:
/**
错误页的tag
*/
extern NSUInteger const HPErrorViewTag;
@class HPErrorView;
@interface UIViewController (HPAdd)
/**
显示错误页
*/
- (void)showErrorView;
/**
移除错误页
*/
- (void)removeErrorView;
/**
检测当前页面是否存在ErrorView
@return ErrorView
*/
- (HPErrorView *)checkErrorViewExist;
@end
内部方法实现,方法调用方式均与直接调用方式时一样,不再赘述。详情参见附件Demo。
自动管理
以上方法适应于大部分场景,但是还是有一些问题,那就是需要自动调用,对于某些特定的场合(比如说数据为空),是否更简单的方式呢?答案是一定的。
考虑到实际使用场景中,展示信息多是使用UITableView或UICollectionView组件,接下来就已UITableView组件为例。
联想实际使用,UITableView与UICollectionView中的reloadData方法估计是最频繁调用的API了,而且是用来重新加载数据的重要方法,因此reloadData方法就是我们今天的主角了。
监听reloadData
需要监听reloadData方法的调用,有多种方式可选,一是直接继承UITableView,在子类中监听;还有一种,就是利用运行时的一些特性。显示,如果项目不是重新开始,自然后一种是更好的选择。新建UITableView分类,替换reloadData
/**
* 在这里将reloadData方法进行替换
*/
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
// When swizzling a class method, use the following:
// Class class = object_getClass((id)self);
// 替换三个方法
SEL originalSelector = @selector(reloadData);
SEL swizzledSelector = @selector(_hp_reloadData);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL needAddMethod =
class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if ( needAddMethod ) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
- 选择是否需要自动管理
由于并不是总是所有的UITableView都需要显示错误页面,所以添加一个控制,只有当设置成自动管理错误页的时候才会触发检查是否需要显示错误页。
@interface UITableView (HPAdd)
/**
是否需要自动管理显示错误页【默认不需要】
*/
@property (nonatomic, assign, getter=isAutoControlErrorView) BOOL autoControlErrorView;
@end
///////////////////////////////////////////////////////////////////
@implementation UITableView (HPAdd)
- (void)_hp_reloadData {
if (self.isAutoControlErrorView) {
[self _checkIsEmpty];
}
[self _hp_reloadData];
}
@end
- 检查是否需要显示错误页
判断当前是否有数据,没有数据则需要显示错误页。
- (void)_checkIsEmpty {
BOOL isEmpty = YES;
id dataSource = self.dataSource;
NSInteger sections = 1; // 默认显示1组
if ([dataSource respondsToSelector:@selector(numberOfSectionsInTableView:)]) {
sections = [dataSource numberOfSectionsInTableView:self];
}
for (NSInteger i = 0; i < sections; i++) {
NSInteger rows = [dataSource tableView:self numberOfRowsInSection:i];
if (rows != 0) {
isEmpty = NO; // 若行数存在,则数据不为空
break;
}
}
dispatch_main_async_safe(^{
if (isEmpty) {
[self _showErrorView]; // 显示错误页
} else {
[self _removeErrorView]; // 移除错误页
}
});
}
总结
对于前两种方法,优点是我们控制起来更加的灵活,可以进行更多个性化的定制;缺点是代码比较重复,而且耦合比较的严重。
对于自动管理,优点是我们不需要关心内部的实现,可以专心写自己的逻辑。其次耦合比较低,分类中更改的代码不会影响到其他地方。缺点是不便于个性化,当需要大量的个性化设置时控制变量就会让代码很不友好了。
另外需要注意的就是,调整UI需要在主线程中进行。Demo请点击