iOS 开发实训第十二周周报

本文详细介绍了iOS开发中自定义控件的实现步骤,包括封装过程和注意事项。同时,深入解析了SDWebImage的内部实现机制,讲解了其内存和硬盘缓存的工作流程,以及如何实现图片的按进度加载。此外,还记录了在开发过程中遇到的合并代码报错问题及其解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、学习笔记

  • iOS自定义View

    • 如果一个view内部的子控件比较多,可以将其封装为一个自定义view,基本流程如下:

      • 重写- (instancetype)initWithFrame:(CGRect)frame方法,在该方法中添加子控件(或者使用懒加载),注意此时不需要设置子控件的frame
      • 重写- (void)layoutSubviews方法,在该方法中设置子控件的frame,注意必须调用[super layoutSubviews];
      • 定义数据模型属性,并重写该属性的set方法,在set方法中取出相应的属性并赋给子控件
      • 如果涉及到对子控件的事件处理,则定义Block属性,并定义对应的set方法,在使用该view的父viewcontroller设置这些Block属性,作为内控事件的回调
    • 示例:

      // .h文件
      #import <UIKit/UIKit.h>
      #import "CustomUIViewModel.h"
      
      @interface CustomUIView : UIView
      // 数据模型
      @property (nonatomic, strong) CustomUIViewModel *model;
      // 点击回调的Block
      @property (nonatomic, copy) void(^labelClick)(void);
      
      // 设置Block的方法
      - (void)setLabelClickWithBlock:(void(^)(void)) labelClickBlock;
      
      @end
      
      
      // .m文件
      #import "CustomUIView.h"
      
      @interface CustomUIView()
      
      @property (nonatomic, strong) UILabel *label;
      
      @end
      
      @implementation CustomUIView
      
      // 1.重写initWithFrame:方法,创建子控件并添加到view里
      - (instancetype)initWithFrame:(CGRect)frame {    
          self = [super initWithFrame:frame];
          if (self) {        
              UILabel *label = [[UILabel alloc] init];
            	// 4.添加TapGesture
            	label.userInteractionEnabled = YES;
              UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTapGesture:)];
              [label addGestureRecognizer:tap];
              self.label = label;
              [self addSubview:label];
          }
          return self;
      }
      
      // 2.重写layoutSubviews,给子控件设置frame
      - (void)layoutSubviews {  
          [super layoutSubviews];
          CGSize size = self.frame.size;
          self.label.frame = CGRectMake(0, 0, size.width * 0.5, size.height * 0.5);
      }
      
      // 3.重写数据模型属性的set方法,给子控件赋值
      - (void)setModel:(CustomUIViewModel *)model {    
          _model = model;
          self.label.text = model.name;
      }
      
      // 4.在TapGesture中调用回调的Block
      - (void)labelTapGesture:(UITapGestureRecognizer *)gestureRecognizer {
          if (self.labelClick) {
              self.labelClick();
          }
      }
      
      // 4.设置Block
      - (void)setLabelClickWithBlock:(void(^)(void)) labelClickBlock {
      		_labelClick = labelClickBlock;
      }
      
      @end
      
    • 两个问题:

      • 为什么自定义view时重写- (instancetype)initWithFrame:(CGRect)frame而不是- (instancetype)init

        • 因为在创建该自定义view的时候,可能使用init也可能使用initWithFrame,但是无论使用哪个,在代码执行的过程中最终一定会调用initWithFrame
      • 为什么只是在- (instancetype)initWithFrame:(CGRect)frame方法中添加子控件而不设置frame,而是在- (void)layoutSubviews设置子控件的frame

        • layoutSubViews方法在以下情况会被触发:

          • 使用init初始化时不会触发layoutSubviews,但是是用initWithFrame 进行初始化时,当rect的值不为CGRectZero时,会触发
          • addSubview会触发layoutSubviews
          • 设置viewFrame会触发layoutSubviews,当然前提是frame的值设置前后发生了变化
          • 滚动一个UIScrollView会触发layoutSubviews
          • 旋转Screen会触发父UIView上的layoutSubviews事件
          • 改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件
        • 那么如果在initWithFrame方法里设置子控件的frame,使用init方法初始化时,比如

          CustomUIView *viewWithInit = [[CustomUIView alloc]init];
          viewWithInit.frame = CGRectMake(10, 300, 300, 100);
          

          虽然init方法最终也会调用initWithFrame方法,但是因为此时这个viewframe还没有设置,self = [super initWithFrame:frame]的结果是一个frame = (0 0; 0 0)view,此时设置子控件的frame是无效的,所以需要在设置了viewframe之后再对子控件重新布局

  • SDWebImage

    • 基本方法:

      // sd_setImageWithURL 设置图片 url
      [self.image sd_setImageWithURL:imagePath];
      
      // completed 设置图片加载完后回调的 block
      [self.image sd_setImageWithURL:imagePath completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
      		// ...        
      }];
      
      // placeholderImage 设置图片加载出来之前使用的默认图片
      [self.image sd_setImageWithURL:imagePath placeholderImage:[UIImage imageNamed:@"default"]];
      
      // options 设置缓存的模式(默认是内存缓存和磁盘缓存结合)
      [self.image sd_setImageWithURL:imagePath placeholderImage:[UIImage imageNamed:@"default"] options:SDWebImageRetryFailed];
      
    • options的可选项:

      // 失败后重试
      SDWebImageRetryFailed = 1 << 0,
            
      // UI交互期间开始下载,会导致延迟下载比如UIScrollView减速
      SDWebImageLowPriority = 1 << 1,
            
      // 只进行内存缓存
      SDWebImageCacheMemoryOnly = 1 << 2,
            
      // 这个标志可以渐进式下载,显示的图像是逐步在下载
      SDWebImageProgressiveDownload = 1 << 3,
            
      // 刷新缓存
      SDWebImageRefreshCached = 1 << 4,
            
      // 后台下载
      SDWebImageContinueInBackground = 1 << 5,
            
      // NSMutableURLRequest.HTTPShouldHandleCookies = YES;
      SDWebImageHandleCookies = 1 << 6,
            
      // 允许使用无效的SSL证书
      SDWebImageAllowInvalidSSLCertificates = 1 << 7,
            
      // 优先下载
      SDWebImageHighPriority = 1 << 8,
            
      // 延迟占位符
      SDWebImageDelayPlaceholder = 1 << 9,
            
      // 改变动画形象
      SDWebImageTransformAnimatedImage = 1 << 10,
      
    • SDWebImage内部实现过程:

      • sd_setImageWithURL:placeholderImage:options: 为例,会先显示 placeholderImage ,然后 SDWebImageManager 根据 URL 开始处理图片
      • SDWebImageManager 调用downloadWithURL:delegate:options:userInfo:,调用 SDImageCachequeryDiskCacheForKey:delegate:userInfo: 方法从缓存查找图片是否已经下载
      • 先到内存缓存中查找是否有图片缓存,如果有则 SDImageCacheDelegate 回调 imageCache:didFindImage:forKey:userInfo:SDWebImageManager
      • SDWebImageManagerDelegate 回调 webImageManager:didFinishWithImage:UIImageView+WebCache 等前端展示图片
      • 如果内存缓存中没有图片缓存,则生成 NSInvocationOperation 添加到队列,根据 URLKey 在硬盘缓存目录下尝试读取图片文件,然后回主线程进行结果回调 notifyDelegate:
      • 如果从硬盘读取到了图片,则将图片添加到内存缓存中(如果空闲内存过小,会先清空内存缓存),SDImageCacheDelegate 回调 imageCache:didFindImage:forKey:userInfo:,进而回调展示图片
      • 如果从硬盘缓存目录读取不到图片,说明所有缓存都不存在该图片,需要下载图片,回调 imageCache:didNotFindImageForKey:userInfo: ,共享或重新生成一个下载器 SDWebImageDownloader 开始下载图片
      • 图片下载用的是 NSURLConnection ,并实现了相关 delegate 来判断图片下载中、下载完成和下载失败,connection:didReceiveData: 中利用 ImageIO 做了按图片下载进度加载效果
      • connectionDidFinishLoading: 数据下载完成后交给 SDWebImageDecoder 做图片解码处理,在一个 NSOperationQueue 完成,不会拖慢主线程
      • 在主线程中 notifyDelegateOnMainThreadWithInfo: 宣告解码完成,imageDecoder:didFinishDecodingImage:userInfo: 回调给 SDWebImageDownloader
      • imageDownloader:didFinishWithImage: 回调给 SDWebImageManager 告知图片下载完成
      • 通知所有的 downloadDelegates 下载完成,回调给需要的地方展示图片
      • 将图片保存到 SDImageCache 中,内存缓存和硬盘缓存同时保存,写文件到硬盘也在以单独 NSInvocationOperation 完成,不会拖慢主线程
      • SDImageCache 在初始化的时候会注册一些消息通知,在内存警告或退到后台的时候清理内存图片缓存,应用结束的时候清理过期图片
      • 可以覆盖其中的某些方法实现自己需要的功能
  • WKWebViewJSOC的交互:

    • OC调用JS

      - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;
      
    • JS调用OC

      // 在JS中调用原生方法
      window.webkit.messageHandlers.<#对象名#>.postMessage(<#参数#>)
      
      // 配置控制器,添加scriptMessageHandler
      [[self.feeeContentWebView configuration].userContentController addScriptMessageHandler:self name:@"<#对象名#>"]; 
      
      // 实现WKScriptMessageHandler的userContentController方法,响应对应的方法
      - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
          if ([message.name isEqualToString:@"<#对象名#>"]) {
            	NSLog(@"%@", message.body); // <#参数#>
              // ...
          }
      }
      
  • WKWebView中的图片实现本地预览:

    • 基本的思路是应用上面讲到的OCJS的交互,在点击HTML中的图片时,就调用原生方法传回来图片的src,然后下载图片,放到一个全屏大小的UIImageView

      // 配置控制器
      [[self.feeeContentWebView configuration].userContentController addScriptMessageHandler:self name:@"imageClick"]; 
      
      
      #pragma mark - WKNavigationDelegate
      
      // JS调用OC
      - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
          [webView evaluateJavaScript:@"function assignImageClickAction(){var imgs=document.getElementsByTagName('img');var length=imgs.length;for(var i=0;i<length;i++){img=imgs[i];img.οnclick=function(){window.webkit.messageHandlers.imageClick.postMessage(this.src)}}}" completionHandler:nil];
          [webView evaluateJavaScript:@"assignImageClickAction();" completionHandler:nil];
      
      }
      
      #pragma mark - WKScriptMessageHandler
      
      // OC调用JS
      - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
          if ([message.name isEqualToString:@"imageClick"]) {
              [self.previewImageView sd_setImageWithURL:message.body completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                  self.previewImageView.backgroundColor = [UIColor blackColor];
                  [self.view bringSubviewToFront:self.previewImageView];
              }];
          }
      }
      
  • WKWebView调整HTML中的文字两端对齐:

    • 通过在htmlString中添加CSS样式实现

      <div style="text-align:justify; text-justify:inter-ideograph;">
      

二、遇到的问题及解决方法

  • 合并代码后报错:

    :-1: Unable to load contents of file list: 'xxxxx/Pods/Target Support Files/Pods-xxxx/Pods-xxxxx-frameworks-Debug-input-files.xcfilelist' (in target 'xxxxx')
    
    :-1: Unable to load contents of file list: 'xxxxx/Pods/Target Support Files/Pods-xxxxx/Pods-xxxxx-frameworks-Debug-output-files.xcfilelist' (in target 'xxxxx')
    
    • 在网上找到的一种解决方法说的是cocoapods的版本不一致,但是更新后发现还是报错

    • srack overflow上找到的另一种方法有效,解决方案如下:

      1.sudo gem update cocoapods --pre
      2.pod update
      3.clean
      4.build
      

三、参考链接


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值