美文网首页DEMOiOS学习iOS程序猿
iOS--高度封装换头像(一句代码实现)

iOS--高度封装换头像(一句代码实现)

作者: shushuzhen | 来源:发表于2016-12-19 21:27 被阅读786次

    最近有点懒,又是很久没有写点东西,就连日记都是前两个月才更新的。当然,找理由真的是我的强项。(哭着笑.脸)

    先上效果图:
    中间随便设置一个ImageView对象就行,然后直接放大招,一句话切换头像。
    代码如下:

    #import "ViewController.h"
    #import "UIViewController+HeadFunction.h"
    
    @interface ViewController ()
    @property (nonatomic, strong) UIImageView *imageView;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
      
        self.view.backgroundColor = [UIColor whiteColor];
        
        _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
        _imageView.center = self.view.center;
        _imageView.image = [UIImage imageNamed:@"头像"];
        _imageView.layer.cornerRadius = _imageView.frame.size.width/2;
        _imageView.layer.masksToBounds = YES;
        
        [self.view addSubview:_imageView];
        
    //  是的,你没看错,就是这一句代码
        [self changeHeadImageWithHeadImageView:_imageView];
    }
    
    - (void)viewWillAppear:(BOOL)animated{
    
        [super viewWillAppear:YES];
        NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
        // 判断沙盒里是否有图片文件
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@HeadImage.png",[userdefaults stringForKey:@"123"]]];   // 保存文件的名称
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL result = [fileManager fileExistsAtPath:filePath];
        if (result) {
            _imageView.image = [UIImage imageWithContentsOfFile:filePath];
        }
        else {
            _imageView.image = [UIImage imageNamed:@"头像"];
        }
    }
    @end
    

    上面那个- (void)viewWillAppear:(BOOL)animated的代码是为了加载出上一次运行时保存在沙盒里的图片,如果沙盒没有,就加载默认设置的。
    最重要的那句代码就是这句啦:
    ** [self changeHeadImageWithHeadImageView:_imageView];**
    我们只需要将ImageView这个对象传进去即可。

    首页面
    点击那个ImageView。出现如下图的弹框。弹框就是用的系统的,一个选择是拍照调用相机,一个是从相册选择,调用系统的相册。也许大家会想,只是写了一句那样的代码怎么会有弹框出现的,是的,这句话里面点进去的那个类里必然是添加了手势的,现在我们可以仔细看看那个一句代码里的具体内容。
    点击弹框
    弹框里的则是两个回调:
    打开相机、打开相册
    里面的AvatarPictureViewController就是自定义的拍照界面。
    #import "UIViewController+HeadFunction.h"
    #import "UIViewController+ActionSheet.h"
    #import <objc/runtime.h>
    
    static const char *HeadManagerKey = "HeadManagerKey";
    static const char *HeadPictureViewKey = "HeadPictureViewKey";
    
    @implementation UIViewController (HeadFunction)
    
    - (void)setHeadPictureView:(UIImageView *)headPictureView {
       // 第一个参数:给哪个对象添加关联
       // 第二个参数:关联的key,通过这个key获取
       // 第三个参数:关联的value
       // 第四个参数:关联的策略
       objc_setAssociatedObject(self, HeadPictureViewKey, headPictureView, OBJC_ASSOCIATION_ASSIGN);
    }
    
    - (UIImageView *)headPictureView {
       return objc_getAssociatedObject(self, HeadPictureViewKey);
    }
    
    - (void)setHeadManager:(HeadManager *)headManager {
       objc_setAssociatedObject(self, HeadManagerKey, headManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    - (HeadManager *)headManager {
       return objc_getAssociatedObject(self, HeadManagerKey);
    }
    
    #pragma mark - ChangeHeadImage
    - (void)changeHeadImageWithHeadImageView:(UIImageView *)headImageView{
       self.headPictureView = headImageView;
       UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headImageChange:)];
       self.headPictureView.userInteractionEnabled = YES;
       [self.headPictureView addGestureRecognizer:tap];
    }
    
    - (void)headImageChange:(UIGestureRecognizer *)tap{
       
       NSNotificationCenter *notificationDefaultCenter = [NSNotificationCenter defaultCenter];
       if (tap.state == UIGestureRecognizerStateEnded) {
           self.headManager = [[HeadManager alloc] initWithTarget:self];
           __weak __typeof(self) weakSelf = self;
           self.headManager.cropImageBlock = ^(UIImage *cropImage){
               weakSelf.headPictureView.image = cropImage;
               [notificationDefaultCenter postNotificationName:headImageUpdateNotificationKey object:nil userInfo:@{headImageValue:cropImage}];
               weakSelf.headManager = nil;
           };
           [self actionSheet:^{
               [self.headManager checkCameraAvailability:^(BOOL auth) {
                   if (!auth) {
                       NSLog(@"没有访问相机权限");
                       return;
                   }
               }];
               
               [self.headManager openTakePhoto];
               
           } ppBlock:^{
               [self.headManager openPhotoalbums];
           }];
       }
       
    }
    
    @end
    

    就是在这里加的tap手势:嘻嘻~~~

    一句代码里的详细内容
    对应的是在这个分类里面:
    分类封装
    在上图可以看出来里面的有个第三方,就是在网上看到的就直接拿过来用了,然后自己再进行了第二次封装,最后就变成了一句代码换了头像。
    在调用相册里的时候,可以在里面进行切换相册。
    详细代码我放在<a href="https://pan.baidu.com/s/1i4PbJ1r ">百度云盘</a> 提取密码: 5vju
    大家可以下载来自己玩!!!

    相关文章

      网友评论

      • 飞奔到宇宙:切换完头像,是不是得保存到数据库或是哪里,下次重新登录,图片好像又没了呢?
        shushuzhen:@飞奔到宇宙 这个是保存到本地的哦 要是要保存到数据库 就可以和后台协商用接口保存哦
      • 潇岩:大神,我改变了图片的位置了为什么图片还在原来的位置没变呢
        shushuzhen:@潇岩 我明天去看看代码呀 应该是哪里把位置给写死了
      • vision_colion::relaxed: 大神带带
      • 微冷归去:666
        shushuzhen:@李不懂 嘻嘻 莹哥来一个
      • 布袋的世界:object-c 表示看不懂 ...
        shushuzhen:@apiapia 你把demo下载下来跑一下就懂了呢
      • Jerry__liu:不错
        shushuzhen:@jerry_YunYun 谢谢 :blush:

      本文标题:iOS--高度封装换头像(一句代码实现)

      本文链接:https://www.haomeiwen.com/subject/rpigmttx.html