iOS实现错误提示页自动管理

疑问?

在开发中我们经常需要用到的组件,自然就是错误页了。一般而言,对于网络错误,数据为空等状态,我们都会在当前的页面中展示一张错误页来提示用户,类似这样:

错误提示页

常用写法

要实现这个需求其实并不难,大概分为以下几种。

  • 直接生成

1. 自定义一个错误页的,就像这样:

#import <UIKit/UIKit.h>

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 <UITableViewDataSource> 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请点击

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 概述在iOS开发中UITableView可以说是使用最广泛的控件,我们平时使用的软件中到处都可以看到它的影子,类似...
    liudhkk阅读 12,958评论 3 38
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,222评论 4 61
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,365评论 30 472
  • 我非常讨厌每个女孩都是漂亮有魅力的公主的鸡汤。WHY?!我为什么要变成被恶龙抢走,被巨人夺走,谁救了国家就嫁...
    苏白迁阅读 1,846评论 0 0
  • 常见有内存泄漏的写法 解决方案 为什么会出现内存泄漏 注:以下均以在主线程new Handler()举例,在其他线...
    画十阅读 1,365评论 0 0