├── .gitignore ├── README.md ├── image ├── .DS_Store ├── person1.gif ├── person2.gif └── 个人主页.gif ├── 个人主页demo.xcodeproj ├── project.pbxproj └── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ └── IDEWorkspaceChecks.plist └── 个人主页demo ├── .DS_Store ├── AppDelegate.h ├── AppDelegate.m ├── Assets.xcassets ├── AppIcon.appiconset │ └── Contents.json ├── Contents.json ├── back.imageset │ ├── Contents.json │ └── back.png ├── cartoon.imageset │ ├── Contents.json │ └── cartoon.jpg ├── center_bg.imageset │ ├── Contents.json │ └── center_bg.jpg ├── message.imageset │ ├── Contents.json │ └── message.png └── shareIcon.imageset │ ├── Contents.json │ ├── 分享@2x.png │ └── 分享@3x.png ├── Base.lproj ├── LaunchScreen.storyboard └── Main.storyboard ├── CCPagedScrollView ├── CCPagedScrollView.h ├── CCPagedScrollView.m ├── XXCustomPageControl.h ├── XXCustomPageControl.m └── directSeedingHeader.h ├── Info.plist ├── PersonCenterChildViewController ├── FirstViewController.h ├── FirstViewController.m ├── FourViewController.h ├── FourViewController.m ├── SecondViewController.h ├── SecondViewController.m ├── ThirdViewController.h └── ThirdViewController.m ├── PersonalCenterViewController.h ├── PersonalCenterViewController.m ├── PrefixHeader.pch ├── SDWebImage ├── LICENSE ├── README.md └── SDWebImage │ ├── NSData+ImageContentType.h │ ├── NSData+ImageContentType.m │ ├── NSImage+WebCache.h │ ├── NSImage+WebCache.m │ ├── SDImageCache.h │ ├── SDImageCache.m │ ├── SDImageCacheConfig.h │ ├── SDImageCacheConfig.m │ ├── SDWebImageCompat.h │ ├── SDWebImageCompat.m │ ├── SDWebImageDecoder.h │ ├── SDWebImageDecoder.m │ ├── SDWebImageDownloader.h │ ├── SDWebImageDownloader.m │ ├── SDWebImageDownloaderOperation.h │ ├── SDWebImageDownloaderOperation.m │ ├── SDWebImageManager.h │ ├── SDWebImageManager.m │ ├── SDWebImageOperation.h │ ├── SDWebImagePrefetcher.h │ ├── SDWebImagePrefetcher.m │ ├── UIButton+WebCache.h │ ├── UIButton+WebCache.m │ ├── UIImage+GIF.h │ ├── UIImage+GIF.m │ ├── UIImage+MultiFormat.h │ ├── UIImage+MultiFormat.m │ ├── UIImageView+HighlightedWebCache.h │ ├── UIImageView+HighlightedWebCache.m │ ├── UIImageView+WebCache.h │ ├── UIImageView+WebCache.m │ ├── UIView+WebCache.h │ ├── UIView+WebCache.m │ ├── UIView+WebCacheOperation.h │ └── UIView+WebCacheOperation.m ├── ViewController.h ├── ViewController.m ├── YWPerson ├── CenterTouchTableView.h ├── CenterTouchTableView.m ├── HMSegmentedControl.h ├── HMSegmentedControl.m ├── SegmentView.h ├── SegmentView.m ├── SegmentViewController.h ├── SegmentViewController.m ├── UIView+Extension.h ├── UIView+Extension.m ├── YWPageHeadView.h └── YWPageHeadView.m └── main.m /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xccheckout 23 | *.xcscmblueprint 24 | 25 | ## Obj-C/Swift specific 26 | *.hmap 27 | *.ipa 28 | *.dSYM.zip 29 | *.dSYM 30 | 31 | # CocoaPods 32 | # 33 | # We recommend against adding the Pods directory to your .gitignore. However 34 | # you should judge for yourself, the pros and cons are mentioned at: 35 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 36 | # 37 | # Pods/ 38 | 39 | # Carthage 40 | # 41 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 42 | # Carthage/Checkouts 43 | 44 | Carthage/Build 45 | 46 | # fastlane 47 | # 48 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 49 | # screenshots whenever they are needed. 50 | # For more information about the recommended setup visit: 51 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 52 | 53 | fastlane/report.xml 54 | fastlane/Preview.html 55 | fastlane/screenshots/**/*.png 56 | fastlane/test_output 57 | 58 | # Code Injection 59 | # 60 | # After new code Injection tools there's a generated folder /iOSInjectionProject 61 | # https://github.com/johnno1962/injectionforxcode 62 | 63 | iOSInjectionProject/ 64 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # YWPersonDemo 2 | 3 | # 介绍 4 | 仿简书微博等个人主页,在此基础上加上头部轮播及下拉轮播放大效果,并且允许左右滑动,如果手势在轮播上,允许左右滑动轮播滚动,上下滑动整体视图滚动,并且附带导航栏渐变效果,本demo下面的可滚动区域支持UITableView,UiScrollView,UICollectionView等视图,瀑布流等也允许 5 | 6 | 7 | #### 视图显示 8 | 9 | * 整体效果 10 | 11 | ![image](https://github.com/china-han/YWPersonDemo/blob/master/image/%E4%B8%AA%E4%BA%BA%E4%B8%BB%E9%A1%B5.gif) 12 | 13 | 14 | * 下部分滑动切换效果 及导航栏渐变效果 15 | 16 | ![image](https://github.com/china-han/YWPersonDemo/blob/master/image/person1.gif) 17 | 18 | * 轮播器滑动效果,允许上下滑动整体页面滑动 左右滑动轮播滑动 19 | 20 | ![image](https://github.com/china-han/YWPersonDemo/blob/master/image/person1.gif) 21 | 22 | 23 | # Requirements 24 | * Xcode 9.4.1 25 | * iOS 8.0 26 | 27 | 28 | # 用法 29 | 因为当时只是想写的demo,所以并没有严格封装 各位可以自己下载demo看一下 这里简单说一下用法 30 | 其中CenterTouchTableView这个类是下面要滑动的各个子类的父类,并且保证各个类存在UITableView,UiScrollView,UICollectionView等可滚动视图 31 | 32 | 33 | 例如demo中下面的UITableView 34 | ``` 35 | @interface FirstViewController : SegmentViewController 36 | 37 | @end 38 | 39 | ``` 40 | ``` 41 | 42 | #import "FirstViewController.h" 43 | 44 | 45 | @interface FirstViewController () < UITableViewDelegate, UITableViewDataSource> 46 | @property (nonatomic, strong) UITableView *tableView; 47 | @property (nonatomic, assign) NSInteger page; 48 | @property (nonatomic, assign) BOOL isHeader; 49 | 50 | @end 51 | 52 | @implementation FirstViewController 53 | 54 | - (void)viewDidLoad { 55 | [super viewDidLoad]; 56 | [self.view addSubview:self.tableView]; 57 | NSLog(@"tableView %f",self.tableView.frame.size.height); 58 | } 59 | 60 | - (UITableView *)tableView { 61 | if (!_tableView) { 62 | _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - NAVHEIGHT - SegmentHeaderViewHeight)]; 63 | // _tableView = [[UITableView alloc] initWithFrame:self.view.bounds]; 64 | _tableView.delegate = self; 65 | _tableView.dataSource = self; 66 | _tableView.showsVerticalScrollIndicator = NO; 67 | _tableView.showsHorizontalScrollIndicator = NO; 68 | _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine; 69 | _tableView.rowHeight = 50; 70 | [self.view addSubview:_tableView]; 71 | } 72 | return _tableView; 73 | } 74 | 75 | #pragma mark - UITableViewDataSource 76 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 77 | return 50; 78 | } 79 | 80 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 81 | static NSString *const FirstViewControllerTableViewCellIdentifier = @"FirstViewControllerTableViewCell"; 82 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FirstViewControllerTableViewCellIdentifier]; 83 | if (cell == nil) { 84 | cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:FirstViewControllerTableViewCellIdentifier]; 85 | } 86 | cell.textLabel.text = [NSString stringWithFormat:@"快点我%ld -> 进入我的消息",indexPath.row]; 87 | return cell; 88 | } 89 | 90 | #pragma mark - UITableViewDelegate 91 | - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 92 | [tableView deselectRowAtIndexPath:indexPath animated:YES]; 93 | 94 | } 95 | 96 | @end 97 | ``` 98 | 99 | 你可以 自定义上半部分视图,如果你也想像我一样支持轮播,并且需要滑动左右轮播,上下滑动整体的话那你需要想我一样把轮播加在YWPageHeadView上面 100 | 例如 101 | ``` 102 | //这是轮播 103 | - (CCPagedScrollView*)imageScrollView{ 104 | if (!_imageScrollView) 105 | { 106 | 107 | _imageScrollView = [[CCPagedScrollView alloc] initWithFrame:CGRectMake(0, 0,kScreenWidth, self.HeaderImageViewHeight) animationDuration:0 isAuto:NO]; 108 | 109 | NSArray *imagesURLStrings = @[ 110 | @"https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a4b3d7085dee3d6d2293d48b252b5910/0e2442a7d933c89524cd5cd4d51373f0830200ea.jpg", 111 | @"https://ss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a41eb338dd33c895a62bcb3bb72e47c2/5fdf8db1cb134954a2192ccb524e9258d1094a1e.jpg", 112 | @"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1542851892&di=0e59ba3566a6124310a0a94a7fe1d3d6&src=http://imgsrc.baidu.com/imgad/pic/item/d52a2834349b033b142032f71ece36d3d539bd77.jpg" 113 | ]; 114 | 115 | NSMutableArray *array = [NSMutableArray array]; 116 | for (NSString *imgUrl in imagesURLStrings) { 117 | [array addObject:[[CCPagedScrollViewItem alloc] initWithItemImageUrl:imgUrl itemTag:@(0)]]; 118 | } 119 | 120 | 121 | _imageScrollView.items = array; 122 | } 123 | 124 | return _imageScrollView; 125 | } 126 | 127 | //这是轮播的父控件 128 | -(YWPageHeadView *)pageHeadView{ 129 | if (!_pageHeadView) { 130 | _pageHeadView = [[YWPageHeadView alloc]init]; 131 | _pageHeadView.parentView = self.view; //这个必须设置 132 | _pageHeadView.frame = CGRectMake(0, -self.offHeight,kScreenWidth, self.HeaderImageViewHeight); 133 | } 134 | return _pageHeadView; 135 | } 136 | ``` 137 | ``` 138 | self.pageHeadView.parentScrollView = self.mainTableView; //这个必须设置 139 | self.pageHeadView.chidlScrollView = self.imageScrollView.scrollView; //这个必须设置 140 | 141 | 142 | [self.mainTableView addSubview:self.pageHeadView]; 143 | [self.pageHeadView addSubview:self.imageScrollView]; 144 | [self.view addSubview:self.naviView]; 145 | ``` 146 | 但是如果你不需要轮播的额外处理,上面只是一个图片存在下拉放大等效果,可以不用YWPageHeadView这个类 直接定义视图加在mainTableView上 147 | 148 | 149 | 另外我为了定义的更加灵活,把轮播视图和下面的红色视图分开定义,加在了mainTableView上,这个可以按需求来,你可以灵活使用 150 | 151 | 152 | 153 | #### 因为时间原因,里面的类名什么的就没有进行规范化处理了,如果使您阅读不便,请原谅一下,如果您有什么更好的建议也可以直接联系我, 154 | #### 最后如果您能点下star支持一下,我会非常感谢😁 155 | 156 | 157 | -------------------------------------------------------------------------------- /image/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/china-han/YWPersonDemo/e9eaab03d106589c58a3bf31321b1d089799e3ac/image/.DS_Store -------------------------------------------------------------------------------- /image/person1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/china-han/YWPersonDemo/e9eaab03d106589c58a3bf31321b1d089799e3ac/image/person1.gif -------------------------------------------------------------------------------- /image/person2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/china-han/YWPersonDemo/e9eaab03d106589c58a3bf31321b1d089799e3ac/image/person2.gif -------------------------------------------------------------------------------- /image/个人主页.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/china-han/YWPersonDemo/e9eaab03d106589c58a3bf31321b1d089799e3ac/image/个人主页.gif -------------------------------------------------------------------------------- /个人主页demo.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /个人主页demo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /个人主页demo/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/china-han/YWPersonDemo/e9eaab03d106589c58a3bf31321b1d089799e3ac/个人主页demo/.DS_Store -------------------------------------------------------------------------------- /个人主页demo/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // 个人主页demo 4 | // 5 | // Created by hyw on 2018/11/14. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /个人主页demo/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // 个人主页demo 4 | // 5 | // Created by hyw on 2018/11/14. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | 11 | @interface AppDelegate () 12 | 13 | @end 14 | 15 | @implementation AppDelegate 16 | 17 | 18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 19 | // Override point for customization after application launch. 20 | return YES; 21 | } 22 | 23 | 24 | - (void)applicationWillResignActive:(UIApplication *)application { 25 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 26 | // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 27 | } 28 | 29 | 30 | - (void)applicationDidEnterBackground:(UIApplication *)application { 31 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 32 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 33 | } 34 | 35 | 36 | - (void)applicationWillEnterForeground:(UIApplication *)application { 37 | // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 38 | } 39 | 40 | 41 | - (void)applicationDidBecomeActive:(UIApplication *)application { 42 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 43 | } 44 | 45 | 46 | - (void)applicationWillTerminate:(UIApplication *)application { 47 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 48 | } 49 | 50 | 51 | @end 52 | -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "20x20", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "20x20", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "29x29", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "29x29", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "40x40", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "40x40", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "size" : "60x60", 36 | "scale" : "2x" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "size" : "60x60", 41 | "scale" : "3x" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "size" : "20x20", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "size" : "20x20", 51 | "scale" : "2x" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "size" : "29x29", 56 | "scale" : "1x" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "size" : "29x29", 61 | "scale" : "2x" 62 | }, 63 | { 64 | "idiom" : "ipad", 65 | "size" : "40x40", 66 | "scale" : "1x" 67 | }, 68 | { 69 | "idiom" : "ipad", 70 | "size" : "40x40", 71 | "scale" : "2x" 72 | }, 73 | { 74 | "idiom" : "ipad", 75 | "size" : "76x76", 76 | "scale" : "1x" 77 | }, 78 | { 79 | "idiom" : "ipad", 80 | "size" : "76x76", 81 | "scale" : "2x" 82 | }, 83 | { 84 | "idiom" : "ipad", 85 | "size" : "83.5x83.5", 86 | "scale" : "2x" 87 | }, 88 | { 89 | "idiom" : "ios-marketing", 90 | "size" : "1024x1024", 91 | "scale" : "1x" 92 | } 93 | ], 94 | "info" : { 95 | "version" : 1, 96 | "author" : "xcode" 97 | } 98 | } -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/back.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "back.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/back.imageset/back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/china-han/YWPersonDemo/e9eaab03d106589c58a3bf31321b1d089799e3ac/个人主页demo/Assets.xcassets/back.imageset/back.png -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/cartoon.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "cartoon.jpg", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/cartoon.imageset/cartoon.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/china-han/YWPersonDemo/e9eaab03d106589c58a3bf31321b1d089799e3ac/个人主页demo/Assets.xcassets/cartoon.imageset/cartoon.jpg -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/center_bg.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "center_bg.jpg", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/center_bg.imageset/center_bg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/china-han/YWPersonDemo/e9eaab03d106589c58a3bf31321b1d089799e3ac/个人主页demo/Assets.xcassets/center_bg.imageset/center_bg.jpg -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/message.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "message.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/message.imageset/message.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/china-han/YWPersonDemo/e9eaab03d106589c58a3bf31321b1d089799e3ac/个人主页demo/Assets.xcassets/message.imageset/message.png -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/shareIcon.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "scale" : "1x" 6 | }, 7 | { 8 | "idiom" : "universal", 9 | "filename" : "分享@2x.png", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "filename" : "分享@3x.png", 15 | "scale" : "3x" 16 | } 17 | ], 18 | "info" : { 19 | "version" : 1, 20 | "author" : "xcode" 21 | } 22 | } -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/shareIcon.imageset/分享@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/china-han/YWPersonDemo/e9eaab03d106589c58a3bf31321b1d089799e3ac/个人主页demo/Assets.xcassets/shareIcon.imageset/分享@2x.png -------------------------------------------------------------------------------- /个人主页demo/Assets.xcassets/shareIcon.imageset/分享@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/china-han/YWPersonDemo/e9eaab03d106589c58a3bf31321b1d089799e3ac/个人主页demo/Assets.xcassets/shareIcon.imageset/分享@3x.png -------------------------------------------------------------------------------- /个人主页demo/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /个人主页demo/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 38 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /个人主页demo/CCPagedScrollView/CCPagedScrollView.h: -------------------------------------------------------------------------------- 1 | // 2 | // CCPagedScrollView.h 3 | // CCPagedScrollView 4 | // 5 | // Created by robbie on 14-8-15. 6 | // Copyright (c) 2014年 wenri365. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "directSeedingHeader.h" 11 | 12 | @class CCPagedScrollViewItem; 13 | @class XXCustomPageControl; 14 | @interface CCPagedScrollView : UIView 15 | 16 | //适配数据 17 | @property(strong,nonatomic)NSArray *items ; 18 | @property (nonatomic, strong)UIScrollView *scrollView; 19 | @property (nonatomic, strong)XXCustomPageControl *pageControl; 20 | @property (nonatomic, assign)BOOL isImageFit; // 是否适应image的大小 21 | 22 | 23 | @property (nonatomic,weak) UIView *parentView; //手势移动的对比view 24 | @property (nonatomic,weak) UIScrollView *parentScrollView; //手势移动的对比view 25 | 26 | -(id)initWithFrame:(CGRect)frame 27 | animationDuration:(NSTimeInterval)animationDuration 28 | isAuto:(BOOL)isAuto; 29 | 30 | 31 | - (void)adjustSubViewHeight; 32 | 33 | //重新轮播 34 | -(void)restartAuto ; 35 | //取消轮播 36 | -(void)stopAuto ; 37 | //指定移动位置 38 | -(void)scrollToIndex:(NSInteger)aIndex ; 39 | 40 | /** 41 | 当点击的时候,执行的block 42 | **/ 43 | @property (nonatomic , copy) void (^TapActionBlock)(CCPagedScrollViewItem *item); 44 | 45 | /** 46 | 切换界面的时候,执行的block 47 | **/ 48 | @property (nonatomic , copy) void (^CurrentIndexBlock)(CCPagedScrollViewItem *item); 49 | 50 | @end 51 | 52 | //辅助信息 53 | @interface CCPagedScrollViewItem : NSObject 54 | 55 | @property (nonatomic, assign)NSInteger itemTag; 56 | @property (nonatomic, strong)NSString *itemImageUrl ; 57 | @property (nonatomic, strong)UIImage *itemImage ; 58 | 59 | 60 | -(id)initWithItemImageUrl:(NSString *)itemImageUrl defaultImage:(UIImage*)itemImage itemTag:(NSInteger)tag ; 61 | -(id)initWithItemImageUrl:(NSString *)itemImageUrl itemTag:(NSInteger)tag ; 62 | -(id)initWithItemImage:(UIImage *)itemImage itemTag:(NSInteger)tag ; 63 | 64 | 65 | @end 66 | -------------------------------------------------------------------------------- /个人主页demo/CCPagedScrollView/XXCustomPageControl.h: -------------------------------------------------------------------------------- 1 | // 2 | // XXCustomPageControl.h 3 | // yaoguoLive 4 | // 5 | // Created by showmac on 2018/11/15. 6 | // Copyright © 2018年 新浪SHOW. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | NS_ASSUME_NONNULL_BEGIN 12 | 13 | @interface XXCustomPageControl : UIPageControl 14 | 15 | @property (nonatomic, strong) UIImage *currentImage; 16 | @property (nonatomic, strong) UIImage *inactiveImage; 17 | 18 | @property (nonatomic, assign) CGSize currentImageSize; 19 | @property (nonatomic, assign) CGSize inactiveImageSize; 20 | 21 | 22 | @end 23 | 24 | NS_ASSUME_NONNULL_END 25 | -------------------------------------------------------------------------------- /个人主页demo/CCPagedScrollView/XXCustomPageControl.m: -------------------------------------------------------------------------------- 1 | // 2 | // XXCustomPageControl.m 3 | // yaoguoLive 4 | // 5 | // Created by showmac on 2018/11/15. 6 | // Copyright © 2018年 新浪SHOW. All rights reserved. 7 | // 8 | 9 | #import "XXCustomPageControl.h" 10 | 11 | 12 | @implementation XXCustomPageControl 13 | 14 | /* 15 | // Only override drawRect: if you perform custom drawing. 16 | // An empty implementation adversely affects performance during animation. 17 | - (void)drawRect:(CGRect)rect { 18 | // Drawing code 19 | } 20 | */ 21 | 22 | - (instancetype)init{ 23 | self = [super init]; 24 | if (self) { 25 | self.userInteractionEnabled = NO; 26 | } 27 | return self; 28 | } 29 | 30 | - (void)setCurrentPage:(NSInteger)currentPage{ 31 | [super setCurrentPage:currentPage]; 32 | 33 | [self updateDots]; 34 | } 35 | 36 | 37 | - (void)updateDots{ 38 | for (int i = 0; i < [self.subviews count]; i++) { 39 | UIImageView *dot = [self imageViewForSubview:[self.subviews objectAtIndex:i] currPage:i]; 40 | if (i == self.currentPage){ 41 | dot.image = self.currentImage; 42 | dot.size = self.currentImageSize; 43 | }else{ 44 | dot.image = self.inactiveImage; 45 | dot.size = self.inactiveImageSize; 46 | } 47 | } 48 | } 49 | - (UIImageView *)imageViewForSubview:(UIView *)view currPage:(int)currPage{ 50 | UIImageView *dot = nil; 51 | if ([view isKindOfClass:[UIView class]]) { 52 | for (UIView *subview in view.subviews) { 53 | if ([subview isKindOfClass:[UIImageView class]]) { 54 | dot = (UIImageView *)subview; 55 | break; 56 | } 57 | } 58 | 59 | if (dot == nil) { 60 | dot = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, view.frame.size.width, view.frame.size.height)]; 61 | 62 | [view addSubview:dot]; 63 | } 64 | }else { 65 | dot = (UIImageView *)view; 66 | } 67 | 68 | return dot; 69 | } 70 | 71 | @end 72 | -------------------------------------------------------------------------------- /个人主页demo/CCPagedScrollView/directSeedingHeader.h: -------------------------------------------------------------------------------- 1 | // 2 | // directSeedingHeader.h 3 | // SinaShow 4 | // 5 | // Created by lurong on 16/4/6. 6 | // Copyright © 2016年 新浪SHOW. All rights reserved. 7 | // 8 | 9 | #ifndef directSeedingHeader_h 10 | #define directSeedingHeader_h 11 | 12 | #import 13 | 14 | 15 | 16 | #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR) 17 | 18 | #define IOS9_OR_LATER (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_8_4) 19 | #define IOS8_OR_LATER (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_8_0) 20 | #define IOS7_OR_LATER (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_7_0) 21 | #define IOS6_OR_LATER (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_6_0) 22 | #define IOS5_OR_LATER (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_5_0) 23 | #define IOS4_OR_LATER (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_4_0) 24 | #define IOS3_OR_LATER (NSFoundationVersionNumber >= NSFoundationVersionNumber_iPhoneOS_3_0) 25 | 26 | #else 27 | 28 | #define IOS6_OR_LATER (NO) 29 | #define IOS5_OR_LATER (NO) 30 | #define IOS4_OR_LATER (NO) 31 | #define IOS3_OR_LATER (NO) 32 | 33 | #endif 34 | 35 | #undef RGB 36 | #define RGB(R,G,B) [UIColor colorWithRed:R/255.0f green:G/255.0f blue:B/255.0f alpha:1.0f] 37 | 38 | #undef RGBA 39 | #define RGBA(R,G,B,A) [UIColor colorWithRed:R/255.0f green:G/255.0f blue:B/255.0f alpha:A] 40 | 41 | #define APPDELEGATE ((AppDelegate *)[UIApplication sharedApplication].delegate) 42 | 43 | #define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width) 44 | #define SCREEN_HEIGTH ([UIScreen mainScreen].bounds.size.height) 45 | 46 | /********** 状态栏高度 **********/ 47 | #define NAVIGATIONBARHEIGHT [[UIApplication sharedApplication] statusBarFrame].size.height 48 | /********** 导航栏高度 **********/ 49 | #define STATUSBARHEIGHT 44 50 | /********** 导航栏+状态栏高度 **********/ 51 | #define NAVHEIGHT (NAVIGATIONBARHEIGHT+STATUSBARHEIGHT) 52 | 53 | #define SegmentHeaderViewHeight 41 //标题栏高度 54 | 55 | 56 | #define AutoSize(px) ((SCREEN_HEIGTH > SCREEN_WIDTH) ? ([UIScreen mainScreen].bounds.size.width/750)*(px) : ([UIScreen mainScreen].bounds.size.height/750)*(px)) 57 | #define BOTTOM_HEIGHT 34 58 | 59 | #define TOP_HEIGHT ([self isIPhoneX] ? 88 : 64) 60 | 61 | #define LIANMAI_light_BACKCOLOR [[UIColor colorWithHexString:@"414141"]colorWithAlphaComponent:0.5]; 62 | #define LIANMAI_grey_BACKCOLOR [[UIColor colorWithHexString:@"414141"]colorWithAlphaComponent:0.7]; 63 | 64 | #define WEAKSELF __block typeof(self) __weak weakSelf = self; 65 | 66 | #define kUIFont(size) [UIFont systemFontOfSize:size] 67 | 68 | 69 | #define VIEWSAFEAREAINSETS(view) ({UIEdgeInsets i; if(@available(iOS 11.0, *)) {i = view.safeAreaInsets;} else {i = UIEdgeInsetsZero;} i;}) 70 | 71 | #define DEF_PURPLE [UIColor colorWithHexString:@"8232ff"] 72 | 73 | 74 | 75 | 76 | #define FONT_SIZE(n) [UIFont systemFontOfSize:n] 77 | #define STATUSBAR_HEIGHT [[UIApplication sharedApplication] statusBarFrame].size.height 78 | 79 | #define DEFAULT_HEAD_IMAGE [UIImage imageNamed:@"Default_Image"] 80 | #define DEFAULT_HEAD_IMAGE_BIG [UIImage imageNamed:@"Default_Image_big"] 81 | #define DEFAULT_LIVEBG_IMAGE [UIImage imageNamed:@"voice_deafultback"] 82 | 83 | #define DEFAULT_BG_COLOR RGB(244, 244, 244) 84 | 85 | #define DEFAULT_MAIN_COLOR DEFAULT_BG_COLOR 86 | 87 | 88 | 89 | 90 | 91 | #define LABEL_COLOR_1 RGB(44,47,49) 92 | #define LABEL_COLOR_2 RGB(101,106,114) 93 | #define LABEL_COLOR_3 RGB(171,174,179) 94 | #define LABEL_COLOR_4 RGB(233, 175, 51) 95 | 96 | #define LABEL_COLOR_6 RGB(255, 210, 102) // 黄色 97 | //#define DEFAULT_COLOR RGB(216, 61, 255) 98 | #define DEFAULT_COLOR [UIColor colorWithHexString:@"A686F6"] 99 | 100 | #define DEFAULT_PURPLE [UIColor colorWithHexString:@"A686F6"] 101 | 102 | #define DEFAULT_PURPLE_USER [UIColor colorWithHexString:@"a686f6"] 103 | 104 | #define LABEL_COLOR_5 DEFAULT_COLOR 105 | 106 | #ifdef HTTPS_SWITCH 107 | 108 | #define ROOM_PIC_URL @"https://img.live.sinashow.com/pic/hall/%@" 109 | #define SMALL_HEAD_URL @"https://img.live.sinashow.com/pic/avatar/%lld_%d_200*200.jpg" // 小头像地址 110 | 111 | #else 112 | 113 | #define ROOM_PIC_URL @"http://img.live.sinashow.com/pic/hall/%@" 114 | #define SMALL_HEAD_URL @"http://img.live.sinashow.com/pic/avatar/%lld_%d_200*200.jpg" // 小头像地址 115 | 116 | #endif 117 | #define DANMU_COLOR RGB(216, 61, 255) 118 | #define SUPER_DANMU_COLOR RGB(255, 102, 0) 119 | #define SUPER_LINK_DANMU_COLOR RGB(62, 130, 255) 120 | 121 | #define ATUSER_NOTIFY @"ATUSER_NOTIFY" 122 | #define FOLLOW @"FOLLOW" 123 | #define SHAREVIEWDISMISS @"SHAREVIEWDISMISS" 124 | #define CHANGE_HEAD_IMAGE @"CHANGE_HEAD_IMAGE" 125 | #define SHOW_PERSION_INFO @"SHOW_PERSION_INFO" 126 | #define OPENCOMMENWEBCTRL @"OPENCOMMENWEBCTRL" 127 | #define LOGINROOM @"LOGINROOM" 128 | #define DOUBLELIVE_BEGIN @"DOUBLELIVE_BEGIN" 129 | #define LAND_MODEL_CHANGED @"LAND_MODEL_CHANGED" 130 | 131 | #define TUIJIAN_OPEN @"TUIJIAN_OPEN" 132 | 133 | #define HOMEOBJ @"HOMEOBJ" 134 | 135 | 136 | #define IsEnablePersonalCenterVCMainTableViewScroll @"IsEnablePersonalCenterVCMainTableViewScroll" 137 | #define PersonalCenterVCBackingStatus @"PersonalCenterVCBackingStatus" 138 | #define SegementViewChildVCBackToTop @"segementViewChildVCBackToTop" 139 | 140 | 141 | 142 | 143 | #endif /* directSeedingHeader_h */ 144 | -------------------------------------------------------------------------------- /个人主页demo/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleDisplayName 8 | wqe 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | UILaunchStoryboardName 26 | LaunchScreen 27 | UIMainStoryboardFile 28 | Main 29 | UIRequiredDeviceCapabilities 30 | 31 | armv7 32 | 33 | UISupportedInterfaceOrientations 34 | 35 | UIInterfaceOrientationPortrait 36 | UIInterfaceOrientationLandscapeLeft 37 | UIInterfaceOrientationLandscapeRight 38 | 39 | UISupportedInterfaceOrientations~ipad 40 | 41 | UIInterfaceOrientationPortrait 42 | UIInterfaceOrientationPortraitUpsideDown 43 | UIInterfaceOrientationLandscapeLeft 44 | UIInterfaceOrientationLandscapeRight 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /个人主页demo/PersonCenterChildViewController/FirstViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // FirstViewController.h 3 | // PersonalCenter 4 | // 5 | // Created by Arch on 2017/6/16. 6 | // Copyright © 2017年 mint_bin. All rights reserved. 7 | // 8 | 9 | #import "SegmentViewController.h" 10 | 11 | @interface FirstViewController : SegmentViewController 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /个人主页demo/PersonCenterChildViewController/FirstViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // FirstViewController.m 3 | // PersonalCenter 4 | // 5 | // Created by Arch on 2017/6/16. 6 | // Copyright © 2017年 mint_bin. All rights reserved. 7 | // 8 | 9 | #import "FirstViewController.h" 10 | 11 | 12 | @interface FirstViewController () < UITableViewDelegate, UITableViewDataSource> 13 | @property (nonatomic, strong) UITableView *tableView; 14 | @property (nonatomic, assign) NSInteger page; 15 | @property (nonatomic, assign) BOOL isHeader; 16 | 17 | @end 18 | 19 | @implementation FirstViewController 20 | 21 | - (void)viewDidLoad { 22 | [super viewDidLoad]; 23 | [self.view addSubview:self.tableView]; 24 | NSLog(@"tableView %f",self.tableView.frame.size.height); 25 | } 26 | 27 | - (UITableView *)tableView { 28 | if (!_tableView) { 29 | _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - NAVHEIGHT - SegmentHeaderViewHeight)]; 30 | // _tableView = [[UITableView alloc] initWithFrame:self.view.bounds]; 31 | _tableView.delegate = self; 32 | _tableView.dataSource = self; 33 | _tableView.showsVerticalScrollIndicator = NO; 34 | _tableView.showsHorizontalScrollIndicator = NO; 35 | _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine; 36 | _tableView.rowHeight = 50; 37 | [self.view addSubview:_tableView]; 38 | } 39 | return _tableView; 40 | } 41 | 42 | #pragma mark - UITableViewDataSource 43 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 44 | return 50; 45 | } 46 | 47 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 48 | static NSString *const FirstViewControllerTableViewCellIdentifier = @"FirstViewControllerTableViewCell"; 49 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FirstViewControllerTableViewCellIdentifier]; 50 | if (cell == nil) { 51 | cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:FirstViewControllerTableViewCellIdentifier]; 52 | } 53 | cell.textLabel.text = [NSString stringWithFormat:@"快点我%ld -> 进入我的消息",indexPath.row]; 54 | return cell; 55 | } 56 | 57 | #pragma mark - UITableViewDelegate 58 | - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 59 | [tableView deselectRowAtIndexPath:indexPath animated:YES]; 60 | 61 | } 62 | 63 | @end 64 | -------------------------------------------------------------------------------- /个人主页demo/PersonCenterChildViewController/FourViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // FourViewController.h 3 | // 个人主页demo 4 | // 5 | // Created by hyw on 2018/11/15. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import "SegmentViewController.h" 10 | 11 | @interface FourViewController : SegmentViewController 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /个人主页demo/PersonCenterChildViewController/FourViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // FourViewController.m 3 | // 个人主页demo 4 | // 5 | // Created by hyw on 2018/11/15. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import "FourViewController.h" 10 | 11 | @interface FourViewController () 12 | @property (nonatomic,strong) UIScrollView *mainScrollView; 13 | @end 14 | 15 | @implementation FourViewController 16 | 17 | - (void)viewDidLoad { 18 | [super viewDidLoad]; 19 | // Do any additional setup after loading the view. 20 | // self.mainScrollView.frame = self.view.bounds; 21 | [self.view addSubview:self.mainScrollView]; 22 | 23 | 24 | UIView *redView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 300)]; 25 | redView.backgroundColor = [UIColor redColor]; 26 | [self.mainScrollView addSubview:redView]; 27 | 28 | UIView *blueView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(redView.frame), kScreenWidth, 300)]; 29 | blueView.backgroundColor = [UIColor blueColor]; 30 | [self.mainScrollView addSubview:blueView]; 31 | 32 | UIView *yelloView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(blueView.frame), kScreenWidth, 300)]; 33 | yelloView.backgroundColor = [UIColor yellowColor]; 34 | [self.mainScrollView addSubview:yelloView]; 35 | 36 | self.mainScrollView.contentSize = CGSizeMake(0, 900); 37 | } 38 | 39 | - (void)didReceiveMemoryWarning { 40 | [super didReceiveMemoryWarning]; 41 | // Dispose of any resources that can be recreated. 42 | } 43 | 44 | -(UIScrollView *)mainScrollView{ 45 | if (!_mainScrollView) { 46 | _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - NAVHEIGHT - SegmentHeaderViewHeight)]; 47 | _mainScrollView.alwaysBounceVertical = YES; 48 | _mainScrollView.showsVerticalScrollIndicator = NO; 49 | _mainScrollView.showsHorizontalScrollIndicator = NO; 50 | _mainScrollView.delegate = self; 51 | _mainScrollView.backgroundColor = [UIColor colorWithRed:242/255. green:242/255. blue:242/255. alpha:1.]; 52 | 53 | } 54 | return _mainScrollView; 55 | } 56 | 57 | @end 58 | -------------------------------------------------------------------------------- /个人主页demo/PersonCenterChildViewController/SecondViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // SecondViewController.h 3 | // PersonalCenter 4 | // 5 | // Created by Arch on 2017/6/16. 6 | // Copyright © 2017年 mint_bin. All rights reserved. 7 | // 8 | 9 | #import "SegmentViewController.h" 10 | 11 | @interface SecondViewController : SegmentViewController 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /个人主页demo/PersonCenterChildViewController/SecondViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // SecondViewController.m 3 | // PersonalCenter 4 | // 5 | // Created by Arch on 2017/6/16. 6 | // Copyright © 2017年 mint_bin. All rights reserved. 7 | // 8 | 9 | #import "SecondViewController.h" 10 | 11 | static NSString *const SecondViewControllerTableVIewCellIdentifier = @"SecondViewControllerTableVIewCell"; 12 | 13 | @interface SecondViewController () 14 | @property(nonatomic, strong) UITableView *tableView; 15 | 16 | @end 17 | 18 | @implementation SecondViewController 19 | - (void)viewDidLoad { 20 | [super viewDidLoad]; 21 | [self creatTableView]; 22 | } 23 | 24 | - (void)creatTableView { 25 | // _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - NAVHEIGHT - SegmentHeaderViewHeight)]; 26 | _tableView = [[UITableView alloc] initWithFrame:self.view.bounds]; 27 | _tableView.delegate = self; 28 | _tableView.dataSource = self; 29 | _tableView.showsVerticalScrollIndicator = NO; 30 | _tableView.showsHorizontalScrollIndicator = NO; 31 | _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine; 32 | _tableView.rowHeight = 50; 33 | [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:SecondViewControllerTableVIewCellIdentifier]; 34 | [self.view addSubview:_tableView]; 35 | } 36 | 37 | #pragma mark - UITableViewDataSource 38 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 39 | return 6; 40 | } 41 | 42 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 43 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SecondViewControllerTableVIewCellIdentifier forIndexPath:indexPath]; 44 | cell.textLabel.text = [NSString stringWithFormat:@"爱晚起,也爱工作到深夜 Row: %ld",indexPath.row]; 45 | cell.imageView.image = [UIImage imageNamed:@"cartoon.jpg"]; 46 | return cell; 47 | } 48 | 49 | - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 50 | [tableView deselectRowAtIndexPath:indexPath animated:YES]; 51 | } 52 | 53 | @end 54 | -------------------------------------------------------------------------------- /个人主页demo/PersonCenterChildViewController/ThirdViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ThirdViewController.h 3 | // PersonalCenter 4 | // 5 | // Created by Arch on 2017/6/16. 6 | // Copyright © 2017年 mint_bin. All rights reserved. 7 | // 8 | 9 | #import "SegmentViewController.h" 10 | 11 | @interface ThirdViewController : SegmentViewController 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /个人主页demo/PersonCenterChildViewController/ThirdViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ThirdViewController.m 3 | // PersonalCenter 4 | // 5 | // Created by Arch on 2017/6/16. 6 | // Copyright © 2017年 mint_bin. All rights reserved. 7 | // 8 | 9 | #import "ThirdViewController.h" 10 | 11 | static NSString *const ThirdViewControllerCollectionViewCellIdentifier = @"ThirdViewControllerCollectionViewCell"; 12 | 13 | @interface ThirdViewController () 14 | @property (nonatomic, strong) UICollectionView *collectionView; 15 | @end 16 | 17 | @implementation ThirdViewController 18 | 19 | - (void)viewDidLoad { 20 | [super viewDidLoad]; 21 | [self.view addSubview:self.collectionView]; 22 | } 23 | 24 | - (UICollectionView *)collectionView { 25 | if (!_collectionView) { 26 | UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init]; 27 | flowLayout.minimumInteritemSpacing = 10; 28 | flowLayout.minimumLineSpacing = 10; 29 | flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 5, 10); 30 | flowLayout.itemSize = CGSizeMake((kScreenWidth - 30) / 2.0, 200); 31 | flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical; 32 | 33 | _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowLayout]; 34 | _collectionView.delegate = self; 35 | _collectionView.dataSource = self; 36 | _collectionView.showsVerticalScrollIndicator = NO; 37 | _collectionView.showsHorizontalScrollIndicator = NO; 38 | //解决在吸顶状态下,当collectionView的内容显示不满屏时(该示例中item <= 6 时会出现)出现竖直方向滑动失效的问题 39 | _collectionView.alwaysBounceVertical = YES; 40 | _collectionView.backgroundColor = [UIColor colorWithRed:242/255. green:242/255. blue:242/255. alpha:1.]; 41 | [_collectionView registerClass :[UICollectionViewCell class] forCellWithReuseIdentifier:ThirdViewControllerCollectionViewCellIdentifier]; 42 | } 43 | return _collectionView; 44 | } 45 | 46 | #pragma mark -- UICollectionViewDataSource 47 | - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { 48 | return 10; 49 | } 50 | 51 | - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 52 | UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:ThirdViewControllerCollectionViewCellIdentifier forIndexPath:indexPath]; 53 | cell.backgroundColor = [UIColor blueColor]; 54 | return cell; 55 | } 56 | 57 | - (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath { 58 | return YES; 59 | } 60 | 61 | @end 62 | -------------------------------------------------------------------------------- /个人主页demo/PersonalCenterViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // PersonalCenterViewController.h 3 | // 个人主页demo 4 | // 5 | // Created by hyw on 2018/11/14. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface PersonalCenterViewController : UIViewController 12 | 13 | //默认上下左右放大 14 | @property (nonatomic, assign) BOOL isEnlarge; 15 | @property (nonatomic, assign) NSUInteger selectedIndex; 16 | @property (nonatomic, readonly, assign) BOOL isBacking; 17 | 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /个人主页demo/PrefixHeader.pch: -------------------------------------------------------------------------------- 1 | // 2 | // PrefixHeader.pch 3 | // PersonalCenter 4 | // 5 | // Created by 赛驰 on 2017/9/15. 6 | // Copyright © 2017年 mint_bin. All rights reserved. 7 | // 8 | 9 | #ifndef PrefixHeader_pch 10 | #define PrefixHeader_pch 11 | 12 | // Include any system framework and library headers here that should be included in all compilation units. 13 | // You will also need to set the Prefix Header build setting of one or more of your targets to reference this file. 14 | //#import 15 | //#import "MBProgressHUD.h" 16 | //#import "MBProgressHUD+NHAdd.h" 17 | //#import 18 | //#import "BaseViewController.h" 19 | 20 | /** notificationName */ 21 | #define IsEnablePersonalCenterVCMainTableViewScroll @"IsEnablePersonalCenterVCMainTableViewScroll" 22 | //#define CurrentSelectedChildViewControllerIndex @"CurrentSelectedChildViewControllerIndex" 23 | #define PersonalCenterVCBackingStatus @"PersonalCenterVCBackingStatus" 24 | #define SegementViewChildVCBackToTop @"segementViewChildVCBackToTop" 25 | 26 | 27 | /********** 屏幕宽高 **********/ 28 | #define kScreenWidth [UIScreen mainScreen].bounds.size.width 29 | #define kScreenHeight [UIScreen mainScreen].bounds.size.height 30 | #define kScreenBounds [UIScreen mainScreen].bounds 31 | 32 | /********** 状态栏高度 **********/ 33 | #define NAVIGATIONBARHEIGHT [[UIApplication sharedApplication] statusBarFrame].size.height 34 | /********** 导航栏高度 **********/ 35 | #define STATUSBARHEIGHT 44 36 | /********** 导航栏+状态栏高度 **********/ 37 | #define NAVHEIGHT (NAVIGATIONBARHEIGHT+STATUSBARHEIGHT) 38 | 39 | 40 | #define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0] 41 | 42 | //宽高比适配 43 | #define AutoSize(px) ((kScreenHeight > kScreenWidth) ? ([UIScreen mainScreen].bounds.size.width/667)*(px) : ([UIScreen mainScreen].bounds.size.height/667)*(px)) 44 | 45 | #define SegmentHeaderViewHeight 41 //标题栏高度 46 | 47 | #define kRGBA(r, g, b, a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a] 48 | 49 | 50 | 51 | 52 | #import "UIView+Extension.h" 53 | 54 | #import "UIImageView+WebCache.h" 55 | 56 | #endif /* PrefixHeader_pch */ 57 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Olivier Poitrey rs@dailymotion.com 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is furnished 8 | to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | 21 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 | 6 | [![Build Status](http://img.shields.io/travis/rs/SDWebImage/master.svg?style=flat)](https://travis-ci.org/rs/SDWebImage) 7 | [![Pod Version](http://img.shields.io/cocoapods/v/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/) 8 | [![Pod Platform](http://img.shields.io/cocoapods/p/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/) 9 | [![Pod License](http://img.shields.io/cocoapods/l/SDWebImage.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0.html) 10 | [![Dependency Status](https://www.versioneye.com/objective-c/sdwebimage/badge.svg?style=flat)](https://www.versioneye.com/objective-c/sdwebimage) 11 | [![Reference Status](https://www.versioneye.com/objective-c/sdwebimage/reference_badge.svg?style=flat)](https://www.versioneye.com/objective-c/sdwebimage/references) 12 | [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/rs/SDWebImage) 13 | [![codecov](https://codecov.io/gh/rs/SDWebImage/branch/master/graph/badge.svg)](https://codecov.io/gh/rs/SDWebImage) 14 | 15 | This library provides an async image downloader with cache support. For convenience, we added categories for UI elements like `UIImageView`, `UIButton`, `MKAnnotationView`. 16 | 17 | ## Features 18 | 19 | - [x] Categories for `UIImageView`, `UIButton`, `MKAnnotationView` adding web image and cache management 20 | - [x] An asynchronous image downloader 21 | - [x] An asynchronous memory + disk image caching with automatic cache expiration handling 22 | - [x] A background image decompression 23 | - [x] A guarantee that the same URL won't be downloaded several times 24 | - [x] A guarantee that bogus URLs won't be retried again and again 25 | - [x] A guarantee that main thread will never be blocked 26 | - [x] Performances! 27 | - [x] Use GCD and ARC 28 | 29 | ## Supported Image Formats 30 | 31 | - Image formats supported by UIImage (JPEG, PNG, ...), including GIF 32 | - WebP format, including animated WebP (use the `WebP` subspec) 33 | 34 | ## Requirements 35 | 36 | - iOS 7.0 or later 37 | - tvOS 9.0 or later 38 | - watchOS 2.0 or later 39 | - OS X 10.8 or later 40 | - Xcode 7.3 or later 41 | 42 | #### Backwards compatibility 43 | 44 | - For iOS 5 and 6, use [any 3.x version up to 3.7.6](https://github.com/rs/SDWebImage/tree/3.7.6) 45 | - For iOS < 5.0, please use the last [2.0 version](https://github.com/rs/SDWebImage/tree/2.0-compat). 46 | 47 | ## Getting Started 48 | 49 | - Read this Readme doc 50 | - Read the [How to use section](https://github.com/rs/SDWebImage#how-to-use) 51 | - Read the [documentation @ CocoaDocs](http://cocoadocs.org/docsets/SDWebImage/) 52 | - Read [How is SDWebImage better than X?](https://github.com/rs/SDWebImage/wiki/How-is-SDWebImage-better-than-X%3F) 53 | - Try the example by downloading the project from Github or even easier using CocoaPods try `pod try SDWebImage` 54 | - Get to the [installation steps](https://github.com/rs/SDWebImage#installation) 55 | - Read the [SDWebImage 4.0 Migration Guide](Docs/SDWebImage-4.0-Migration-guide.md) to get an idea of the changes from 3.x to 4.x 56 | 57 | ## Who Uses It 58 | - Find out [who uses SDWebImage](https://github.com/rs/SDWebImage/wiki/Who-Uses-SDWebImage) and add your app to the list. 59 | 60 | ## Communication 61 | 62 | - If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/sdwebimage). (Tag 'sdwebimage') 63 | - If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/sdwebimage). 64 | - If you **found a bug**, open an issue. 65 | - If you **have a feature request**, open an issue. 66 | - If you **want to contribute**, submit a pull request. 67 | 68 | ## Installation 69 | 70 | ## How To Use 71 | 72 | ```objective-c 73 | Objective-C: 74 | 75 | #import 76 | ... 77 | [imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] 78 | placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; 79 | ``` 80 | 81 | ```swift 82 | Swift: 83 | 84 | @import SDWebImage 85 | 86 | imageView.sd_setImage(with: URL(string: "http://www.domain.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png")) 87 | ``` 88 | 89 | - For details about how to use the library and clear examples, see [The detailed How to use](Docs/HowToUse.md) 90 | 91 | ## Animated Images (GIF) support 92 | 93 | - Starting with the 4.0 version, we rely on [FLAnimatedImage](https://github.com/Flipboard/FLAnimatedImage) to take care of our animated images. 94 | - To use it, simply make sure you use `FLAnimatedImageView` instead of `UIImageView`. 95 | - **Note**: there is a backwards compatible feature, so if you are still trying to load a GIF into a `UIImageView`, it will only show the 1st frame as a static image. 96 | - **Important**: FLAnimatedImage only works on the iOS platform, so for all the other platforms (OS X, tvOS, watchOS) we will fallback to the backwards compatibility feature described above 97 | 98 | Common Problems 99 | --------------- 100 | 101 | ### Using dynamic image size with UITableViewCell 102 | 103 | UITableView determines the size of the image by the first image set for a cell. If your remote images 104 | don't have the same size as your placeholder image, you may experience strange anamorphic scaling issue. 105 | The following article gives a way to workaround this issue: 106 | 107 | [http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/](http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/) 108 | 109 | 110 | ### Handle image refresh 111 | 112 | SDWebImage does very aggressive caching by default. It ignores all kind of caching control header returned by the HTTP server and cache the returned images with no time restriction. It implies your images URLs are static URLs pointing to images that never change. If the pointed image happen to change, some parts of the URL should change accordingly. 113 | 114 | If you don't control the image server you're using, you may not be able to change the URL when its content is updated. This is the case for Facebook avatar URLs for instance. In such case, you may use the `SDWebImageRefreshCached` flag. This will slightly degrade the performance but will respect the HTTP caching control headers: 115 | 116 | ``` objective-c 117 | [imageView sd_setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"] 118 | placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"] 119 | options:SDWebImageRefreshCached]; 120 | ``` 121 | 122 | ### Add a progress indicator 123 | 124 | Add these before you call ```sd_setImageWithURL``` 125 | 126 | ``` objective-c 127 | [imageView setShowActivityIndicatorView:YES]; 128 | [imageView setIndicatorStyle:UIActivityIndicatorViewStyleGray]; 129 | ``` 130 | 131 | ``` swift 132 | imageView.setShowActivityIndicatorView(true) 133 | imageView.setIndicatorStyle(.Gray) 134 | ``` 135 | 136 | Installation 137 | ------------ 138 | 139 | There are three ways to use SDWebImage in your project: 140 | - using CocoaPods 141 | - using Carthage 142 | - by cloning the project into your repository 143 | 144 | ### Installation with CocoaPods 145 | 146 | [CocoaPods](http://cocoapods.org/) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries in your projects. See the [Get Started](http://cocoapods.org/#get_started) section for more details. 147 | 148 | #### Podfile 149 | ``` 150 | platform :ios, '7.0' 151 | pod 'SDWebImage', '~>3.8' 152 | ``` 153 | 154 | If you are using Swift, be sure to add `use_frameworks!` and set your target to iOS 8+: 155 | ``` 156 | platform :ios, '8.0' 157 | use_frameworks! 158 | ``` 159 | 160 | #### Subspecs 161 | 162 | There are 3 subspecs available now: `Core`, `MapKit` and `WebP` (this means you can install only some of the SDWebImage modules. By default, you get just `Core`, so if you need `WebP`, you need to specify it). 163 | 164 | Podfile example: 165 | ``` 166 | pod 'SDWebImage/WebP' 167 | ``` 168 | 169 | ### Installation with Carthage (iOS 8+) 170 | 171 | [Carthage](https://github.com/Carthage/Carthage) is a lightweight dependency manager for Swift and Objective-C. It leverages CocoaTouch modules and is less invasive than CocoaPods. 172 | 173 | To install with carthage, follow the instruction on [Carthage](https://github.com/Carthage/Carthage) 174 | 175 | #### Cartfile 176 | ``` 177 | github "rs/SDWebImage" 178 | ``` 179 | 180 | ### Installation by cloning the repository 181 | - see [Manual install](Docs/ManualInstallation.md) 182 | 183 | ### Import headers in your source files 184 | 185 | In the source files where you need to use the library, import the header file: 186 | 187 | ```objective-c 188 | #import 189 | ``` 190 | 191 | ### Build Project 192 | 193 | At this point your workspace should build without error. If you are having problem, post to the Issue and the 194 | community can help you solve it. 195 | 196 | ## Author 197 | - [Olivier Poitrey](https://github.com/rs) 198 | 199 | ## Collaborators 200 | - [Konstantinos K.](https://github.com/mythodeia) 201 | - [Bogdan Poplauschi](https://github.com/bpoplauschi) 202 | 203 | ## Licenses 204 | 205 | All source code is licensed under the [MIT License](https://raw.github.com/rs/SDWebImage/master/LICENSE). 206 | 207 | ## Architecture 208 | 209 |

210 | 211 |

212 | 213 |

214 | 215 |

216 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/NSData+ImageContentType.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * (c) Fabrice Aneche 5 | * 6 | * For the full copyright and license information, please view the LICENSE 7 | * file that was distributed with this source code. 8 | */ 9 | 10 | #import 11 | #import "SDWebImageCompat.h" 12 | 13 | typedef NS_ENUM(NSInteger, SDImageFormat) { 14 | SDImageFormatUndefined = -1, 15 | SDImageFormatJPEG = 0, 16 | SDImageFormatPNG, 17 | SDImageFormatGIF, 18 | SDImageFormatTIFF, 19 | SDImageFormatWebP 20 | }; 21 | 22 | @interface NSData (ImageContentType) 23 | 24 | /** 25 | * Return image format 26 | * 27 | * @param data the input image data 28 | * 29 | * @return the image format as `SDImageFormat` (enum) 30 | */ 31 | + (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data; 32 | 33 | @end 34 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/NSData+ImageContentType.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * (c) Fabrice Aneche 5 | * 6 | * For the full copyright and license information, please view the LICENSE 7 | * file that was distributed with this source code. 8 | */ 9 | 10 | #import "NSData+ImageContentType.h" 11 | 12 | 13 | @implementation NSData (ImageContentType) 14 | 15 | + (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data { 16 | if (!data) { 17 | return SDImageFormatUndefined; 18 | } 19 | 20 | uint8_t c; 21 | [data getBytes:&c length:1]; 22 | switch (c) { 23 | case 0xFF: 24 | return SDImageFormatJPEG; 25 | case 0x89: 26 | return SDImageFormatPNG; 27 | case 0x47: 28 | return SDImageFormatGIF; 29 | case 0x49: 30 | case 0x4D: 31 | return SDImageFormatTIFF; 32 | case 0x52: 33 | // R as RIFF for WEBP 34 | if (data.length < 12) { 35 | return SDImageFormatUndefined; 36 | } 37 | 38 | NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; 39 | if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { 40 | return SDImageFormatWebP; 41 | } 42 | } 43 | return SDImageFormatUndefined; 44 | } 45 | 46 | @end 47 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/NSImage+WebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | 11 | #if SD_MAC 12 | 13 | #import 14 | 15 | @interface NSImage (WebCache) 16 | 17 | - (CGImageRef)CGImage; 18 | - (NSArray *)images; 19 | - (BOOL)isGIF; 20 | 21 | @end 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/NSImage+WebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "NSImage+WebCache.h" 10 | 11 | #if SD_MAC 12 | 13 | @implementation NSImage (WebCache) 14 | 15 | - (CGImageRef)CGImage { 16 | NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); 17 | CGImageRef cgImage = [self CGImageForProposedRect:&imageRect context:NULL hints:nil]; 18 | return cgImage; 19 | } 20 | 21 | - (NSArray *)images { 22 | return nil; 23 | } 24 | 25 | - (BOOL)isGIF { 26 | return NO; 27 | } 28 | 29 | @end 30 | 31 | #endif 32 | 33 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/SDImageCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | 12 | @class SDImageCacheConfig; 13 | 14 | typedef NS_ENUM(NSInteger, SDImageCacheType) { 15 | /** 16 | * The image wasn't available the SDWebImage caches, but was downloaded from the web. 17 | */ 18 | SDImageCacheTypeNone, 19 | /** 20 | * The image was obtained from the disk cache. 21 | */ 22 | SDImageCacheTypeDisk, 23 | /** 24 | * The image was obtained from the memory cache. 25 | */ 26 | SDImageCacheTypeMemory 27 | }; 28 | 29 | typedef void(^SDCacheQueryCompletedBlock)(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType); 30 | 31 | typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache); 32 | 33 | typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); 34 | 35 | 36 | /** 37 | * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed 38 | * asynchronous so it doesn’t add unnecessary latency to the UI. 39 | */ 40 | @interface SDImageCache : NSObject 41 | 42 | #pragma mark - Properties 43 | 44 | /** 45 | * Cache Config object - storing all kind of settings 46 | */ 47 | @property (nonatomic, nonnull, readonly) SDImageCacheConfig *config; 48 | 49 | /** 50 | * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. 51 | */ 52 | @property (assign, nonatomic) NSUInteger maxMemoryCost; 53 | 54 | /** 55 | * The maximum number of objects the cache should hold. 56 | */ 57 | @property (assign, nonatomic) NSUInteger maxMemoryCountLimit; 58 | 59 | #pragma mark - Singleton and initialization 60 | 61 | /** 62 | * Returns global shared cache instance 63 | * 64 | * @return SDImageCache global instance 65 | */ 66 | + (nonnull instancetype)sharedImageCache; 67 | 68 | /** 69 | * Init a new cache store with a specific namespace 70 | * 71 | * @param ns The namespace to use for this cache store 72 | */ 73 | - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns; 74 | 75 | /** 76 | * Init a new cache store with a specific namespace and directory 77 | * 78 | * @param ns The namespace to use for this cache store 79 | * @param directory Directory to cache disk images in 80 | */ 81 | - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns 82 | diskCacheDirectory:(nonnull NSString *)directory NS_DESIGNATED_INITIALIZER; 83 | 84 | #pragma mark - Cache paths 85 | 86 | - (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace; 87 | 88 | /** 89 | * Add a read-only cache path to search for images pre-cached by SDImageCache 90 | * Useful if you want to bundle pre-loaded images with your app 91 | * 92 | * @param path The path to use for this read-only cache path 93 | */ 94 | - (void)addReadOnlyCachePath:(nonnull NSString *)path; 95 | 96 | #pragma mark - Store Ops 97 | 98 | /** 99 | * Asynchronously store an image into memory and disk cache at the given key. 100 | * 101 | * @param image The image to store 102 | * @param key The unique image cache key, usually it's image absolute URL 103 | * @param completionBlock A block executed after the operation is finished 104 | */ 105 | - (void)storeImage:(nullable UIImage *)image 106 | forKey:(nullable NSString *)key 107 | completion:(nullable SDWebImageNoParamsBlock)completionBlock; 108 | 109 | /** 110 | * Asynchronously store an image into memory and disk cache at the given key. 111 | * 112 | * @param image The image to store 113 | * @param key The unique image cache key, usually it's image absolute URL 114 | * @param toDisk Store the image to disk cache if YES 115 | * @param completionBlock A block executed after the operation is finished 116 | */ 117 | - (void)storeImage:(nullable UIImage *)image 118 | forKey:(nullable NSString *)key 119 | toDisk:(BOOL)toDisk 120 | completion:(nullable SDWebImageNoParamsBlock)completionBlock; 121 | 122 | /** 123 | * Asynchronously store an image into memory and disk cache at the given key. 124 | * 125 | * @param image The image to store 126 | * @param imageData The image data as returned by the server, this representation will be used for disk storage 127 | * instead of converting the given image object into a storable/compressed image format in order 128 | * to save quality and CPU 129 | * @param key The unique image cache key, usually it's image absolute URL 130 | * @param toDisk Store the image to disk cache if YES 131 | * @param completionBlock A block executed after the operation is finished 132 | */ 133 | - (void)storeImage:(nullable UIImage *)image 134 | imageData:(nullable NSData *)imageData 135 | forKey:(nullable NSString *)key 136 | toDisk:(BOOL)toDisk 137 | completion:(nullable SDWebImageNoParamsBlock)completionBlock; 138 | 139 | /** 140 | * Synchronously store image NSData into disk cache at the given key. 141 | * 142 | * @warning This method is synchronous, make sure to call it from the ioQueue 143 | * 144 | * @param imageData The image data to store 145 | * @param key The unique image cache key, usually it's image absolute URL 146 | */ 147 | - (void)storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key; 148 | 149 | #pragma mark - Query and Retrieve Ops 150 | 151 | /** 152 | * Async check if image exists in disk cache already (does not load the image) 153 | * 154 | * @param key the key describing the url 155 | * @param completionBlock the block to be executed when the check is done. 156 | * @note the completion block will be always executed on the main queue 157 | */ 158 | - (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock; 159 | 160 | /** 161 | * Operation that queries the cache asynchronously and call the completion when done. 162 | * 163 | * @param key The unique key used to store the wanted image 164 | * @param doneBlock The completion block. Will not get called if the operation is cancelled 165 | * 166 | * @return a NSOperation instance containing the cache op 167 | */ 168 | - (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDCacheQueryCompletedBlock)doneBlock; 169 | 170 | /** 171 | * Query the memory cache synchronously. 172 | * 173 | * @param key The unique key used to store the image 174 | */ 175 | - (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key; 176 | 177 | /** 178 | * Query the disk cache synchronously. 179 | * 180 | * @param key The unique key used to store the image 181 | */ 182 | - (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key; 183 | 184 | /** 185 | * Query the cache (memory and or disk) synchronously after checking the memory cache. 186 | * 187 | * @param key The unique key used to store the image 188 | */ 189 | - (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key; 190 | 191 | #pragma mark - Remove Ops 192 | 193 | /** 194 | * Remove the image from memory and disk cache asynchronously 195 | * 196 | * @param key The unique image cache key 197 | * @param completion A block that should be executed after the image has been removed (optional) 198 | */ 199 | - (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion; 200 | 201 | /** 202 | * Remove the image from memory and optionally disk cache asynchronously 203 | * 204 | * @param key The unique image cache key 205 | * @param fromDisk Also remove cache entry from disk if YES 206 | * @param completion A block that should be executed after the image has been removed (optional) 207 | */ 208 | - (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion; 209 | 210 | #pragma mark - Cache clean Ops 211 | 212 | /** 213 | * Clear all memory cached images 214 | */ 215 | - (void)clearMemory; 216 | 217 | /** 218 | * Async clear all disk cached images. Non-blocking method - returns immediately. 219 | * @param completion A block that should be executed after cache expiration completes (optional) 220 | */ 221 | - (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion; 222 | 223 | /** 224 | * Async remove all expired cached image from disk. Non-blocking method - returns immediately. 225 | * @param completionBlock A block that should be executed after cache expiration completes (optional) 226 | */ 227 | - (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock; 228 | 229 | #pragma mark - Cache Info 230 | 231 | /** 232 | * Get the size used by the disk cache 233 | */ 234 | - (NSUInteger)getSize; 235 | 236 | /** 237 | * Get the number of images in the disk cache 238 | */ 239 | - (NSUInteger)getDiskCount; 240 | 241 | /** 242 | * Asynchronously calculate the disk cache's size. 243 | */ 244 | - (void)calculateSizeWithCompletionBlock:(nullable SDWebImageCalculateSizeBlock)completionBlock; 245 | 246 | #pragma mark - Cache Paths 247 | 248 | /** 249 | * Get the cache path for a certain key (needs the cache path root folder) 250 | * 251 | * @param key the key (can be obtained from url using cacheKeyForURL) 252 | * @param path the cache path root folder 253 | * 254 | * @return the cache path 255 | */ 256 | - (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path; 257 | 258 | /** 259 | * Get the default cache path for a certain key 260 | * 261 | * @param key the key (can be obtained from url using cacheKeyForURL) 262 | * 263 | * @return the default cache path 264 | */ 265 | - (nullable NSString *)defaultCachePathForKey:(nullable NSString *)key; 266 | 267 | @end 268 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/SDImageCacheConfig.h: -------------------------------------------------------------------------------- 1 | // 2 | // SDImageCacheConfig.h 3 | // SDWebImage 4 | // 5 | // Created by Bogdan on 09/09/16. 6 | // Copyright © 2016 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | 12 | @interface SDImageCacheConfig : NSObject 13 | 14 | /** 15 | * Decompressing images that are downloaded and cached can improve performance but can consume lot of memory. 16 | * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. 17 | */ 18 | @property (assign, nonatomic) BOOL shouldDecompressImages; 19 | 20 | /** 21 | * disable iCloud backup [defaults to YES] 22 | */ 23 | @property (assign, nonatomic) BOOL shouldDisableiCloud; 24 | 25 | /** 26 | * use memory cache [defaults to YES] 27 | */ 28 | @property (assign, nonatomic) BOOL shouldCacheImagesInMemory; 29 | 30 | /** 31 | * The maximum length of time to keep an image in the cache, in seconds 32 | */ 33 | @property (assign, nonatomic) NSInteger maxCacheAge; 34 | 35 | /** 36 | * The maximum size of the cache, in bytes. 37 | */ 38 | @property (assign, nonatomic) NSUInteger maxCacheSize; 39 | 40 | @end 41 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/SDImageCacheConfig.m: -------------------------------------------------------------------------------- 1 | // 2 | // SDImageCacheConfig.m 3 | // SDWebImage 4 | // 5 | // Created by Bogdan on 09/09/16. 6 | // Copyright © 2016 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "SDImageCacheConfig.h" 10 | 11 | static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week 12 | 13 | @implementation SDImageCacheConfig 14 | 15 | - (instancetype)init { 16 | if (self = [super init]) { 17 | _shouldDecompressImages = YES; 18 | _shouldDisableiCloud = YES; 19 | _shouldCacheImagesInMemory = YES; 20 | _maxCacheAge = kDefaultCacheMaxCacheAge; 21 | _maxCacheSize = 0; 22 | } 23 | return self; 24 | } 25 | 26 | @end 27 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/SDWebImageCompat.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * (c) Jamie Pinkham 5 | * 6 | * For the full copyright and license information, please view the LICENSE 7 | * file that was distributed with this source code. 8 | */ 9 | 10 | #import 11 | 12 | #ifdef __OBJC_GC__ 13 | #error SDWebImage does not support Objective-C Garbage Collection 14 | #endif 15 | 16 | // Apple's defines from TargetConditionals.h are a bit weird. 17 | // Seems like TARGET_OS_MAC is always defined (on all platforms). 18 | // To determine if we are running on OSX, we can only relly on TARGET_OS_IPHONE=0 and all the other platforms 19 | #if !TARGET_OS_IPHONE && !TARGET_OS_IOS && !TARGET_OS_TV && !TARGET_OS_WATCH 20 | #define SD_MAC 1 21 | #else 22 | #define SD_MAC 0 23 | #endif 24 | 25 | // iOS and tvOS are very similar, UIKit exists on both platforms 26 | // Note: watchOS also has UIKit, but it's very limited 27 | #if TARGET_OS_IOS || TARGET_OS_TV 28 | #define SD_UIKIT 1 29 | #else 30 | #define SD_UIKIT 0 31 | #endif 32 | 33 | #if TARGET_OS_IOS 34 | #define SD_IOS 1 35 | #else 36 | #define SD_IOS 0 37 | #endif 38 | 39 | #if TARGET_OS_TV 40 | #define SD_TV 1 41 | #else 42 | #define SD_TV 0 43 | #endif 44 | 45 | #if TARGET_OS_WATCH 46 | #define SD_WATCH 1 47 | #else 48 | #define SD_WATCH 0 49 | #endif 50 | 51 | 52 | #if SD_MAC 53 | #import 54 | #ifndef UIImage 55 | #define UIImage NSImage 56 | #endif 57 | #ifndef UIImageView 58 | #define UIImageView NSImageView 59 | #endif 60 | #ifndef UIView 61 | #define UIView NSView 62 | #endif 63 | #else 64 | #if __IPHONE_OS_VERSION_MIN_REQUIRED != 20000 && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 65 | #error SDWebImage doesn't support Deployment Target version < 5.0 66 | #endif 67 | 68 | #if SD_UIKIT 69 | #import 70 | #endif 71 | #if SD_WATCH 72 | #import 73 | #endif 74 | #endif 75 | 76 | #ifndef NS_ENUM 77 | #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type 78 | #endif 79 | 80 | #ifndef NS_OPTIONS 81 | #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type 82 | #endif 83 | 84 | #if OS_OBJECT_USE_OBJC 85 | #undef SDDispatchQueueRelease 86 | #undef SDDispatchQueueSetterSementics 87 | #define SDDispatchQueueRelease(q) 88 | #define SDDispatchQueueSetterSementics strong 89 | #else 90 | #undef SDDispatchQueueRelease 91 | #undef SDDispatchQueueSetterSementics 92 | #define SDDispatchQueueRelease(q) (dispatch_release(q)) 93 | #define SDDispatchQueueSetterSementics assign 94 | #endif 95 | 96 | extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image); 97 | 98 | typedef void(^SDWebImageNoParamsBlock)(); 99 | 100 | extern NSString *const SDWebImageErrorDomain; 101 | 102 | #ifndef dispatch_main_async_safe 103 | #define dispatch_main_async_safe(block)\ 104 | if (strcmp(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL), dispatch_queue_get_label(dispatch_get_main_queue())) == 0) {\ 105 | block();\ 106 | } else {\ 107 | dispatch_async(dispatch_get_main_queue(), block);\ 108 | } 109 | #endif 110 | 111 | static int64_t kAsyncTestTimeout = 5; 112 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/SDWebImageCompat.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | 11 | #if !__has_feature(objc_arc) 12 | #error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag 13 | #endif 14 | 15 | inline UIImage *SDScaledImageForKey(NSString * _Nullable key, UIImage * _Nullable image) { 16 | if (!image) { 17 | return nil; 18 | } 19 | 20 | #if SD_MAC 21 | return image; 22 | #elif SD_UIKIT || SD_WATCH 23 | if ((image.images).count > 0) { 24 | NSMutableArray *scaledImages = [NSMutableArray array]; 25 | 26 | for (UIImage *tempImage in image.images) { 27 | [scaledImages addObject:SDScaledImageForKey(key, tempImage)]; 28 | } 29 | 30 | return [UIImage animatedImageWithImages:scaledImages duration:image.duration]; 31 | } 32 | else { 33 | #if SD_WATCH 34 | if ([[WKInterfaceDevice currentDevice] respondsToSelector:@selector(screenScale)]) { 35 | #elif SD_UIKIT 36 | if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { 37 | #endif 38 | CGFloat scale = 1; 39 | if (key.length >= 8) { 40 | NSRange range = [key rangeOfString:@"@2x."]; 41 | if (range.location != NSNotFound) { 42 | scale = 2.0; 43 | } 44 | 45 | range = [key rangeOfString:@"@3x."]; 46 | if (range.location != NSNotFound) { 47 | scale = 3.0; 48 | } 49 | } 50 | 51 | UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; 52 | image = scaledImage; 53 | } 54 | return image; 55 | } 56 | #endif 57 | } 58 | 59 | NSString *const SDWebImageErrorDomain = @"SDWebImageErrorDomain"; 60 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/SDWebImageDecoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * (c) james 5 | * 6 | * For the full copyright and license information, please view the LICENSE 7 | * file that was distributed with this source code. 8 | */ 9 | 10 | #import 11 | #import "SDWebImageCompat.h" 12 | 13 | @interface UIImage (ForceDecode) 14 | 15 | + (nullable UIImage *)decodedImageWithImage:(nullable UIImage *)image; 16 | 17 | + (nullable UIImage *)decodedAndScaledDownImageWithImage:(nullable UIImage *)image; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/SDWebImageDownloader.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | #import "SDWebImageOperation.h" 12 | 13 | typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { 14 | SDWebImageDownloaderLowPriority = 1 << 0, 15 | SDWebImageDownloaderProgressiveDownload = 1 << 1, 16 | 17 | /** 18 | * By default, request prevent the use of NSURLCache. With this flag, NSURLCache 19 | * is used with default policies. 20 | */ 21 | SDWebImageDownloaderUseNSURLCache = 1 << 2, 22 | 23 | /** 24 | * Call completion block with nil image/imageData if the image was read from NSURLCache 25 | * (to be combined with `SDWebImageDownloaderUseNSURLCache`). 26 | */ 27 | 28 | SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, 29 | /** 30 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for 31 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled. 32 | */ 33 | 34 | SDWebImageDownloaderContinueInBackground = 1 << 4, 35 | 36 | /** 37 | * Handles cookies stored in NSHTTPCookieStore by setting 38 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES; 39 | */ 40 | SDWebImageDownloaderHandleCookies = 1 << 5, 41 | 42 | /** 43 | * Enable to allow untrusted SSL certificates. 44 | * Useful for testing purposes. Use with caution in production. 45 | */ 46 | SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, 47 | 48 | /** 49 | * Put the image in the high priority queue. 50 | */ 51 | SDWebImageDownloaderHighPriority = 1 << 7, 52 | 53 | /** 54 | * Scale down the image 55 | */ 56 | SDWebImageDownloaderScaleDownLargeImages = 1 << 8, 57 | }; 58 | 59 | typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { 60 | /** 61 | * Default value. All download operations will execute in queue style (first-in-first-out). 62 | */ 63 | SDWebImageDownloaderFIFOExecutionOrder, 64 | 65 | /** 66 | * All download operations will execute in stack style (last-in-first-out). 67 | */ 68 | SDWebImageDownloaderLIFOExecutionOrder 69 | }; 70 | 71 | extern NSString * _Nonnull const SDWebImageDownloadStartNotification; 72 | extern NSString * _Nonnull const SDWebImageDownloadStopNotification; 73 | 74 | typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL); 75 | 76 | typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished); 77 | 78 | typedef NSDictionary SDHTTPHeadersDictionary; 79 | typedef NSMutableDictionary SDHTTPHeadersMutableDictionary; 80 | 81 | typedef SDHTTPHeadersDictionary * _Nullable (^SDWebImageDownloaderHeadersFilterBlock)(NSURL * _Nullable url, SDHTTPHeadersDictionary * _Nullable headers); 82 | 83 | /** 84 | * A token associated with each download. Can be used to cancel a download 85 | */ 86 | @interface SDWebImageDownloadToken : NSObject 87 | 88 | @property (nonatomic, strong, nullable) NSURL *url; 89 | @property (nonatomic, strong, nullable) id downloadOperationCancelToken; 90 | 91 | @end 92 | 93 | 94 | /** 95 | * Asynchronous downloader dedicated and optimized for image loading. 96 | */ 97 | @interface SDWebImageDownloader : NSObject 98 | 99 | /** 100 | * Decompressing images that are downloaded and cached can improve performance but can consume lot of memory. 101 | * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. 102 | */ 103 | @property (assign, nonatomic) BOOL shouldDecompressImages; 104 | 105 | /** 106 | * The maximum number of concurrent downloads 107 | */ 108 | @property (assign, nonatomic) NSInteger maxConcurrentDownloads; 109 | 110 | /** 111 | * Shows the current amount of downloads that still need to be downloaded 112 | */ 113 | @property (readonly, nonatomic) NSUInteger currentDownloadCount; 114 | 115 | 116 | /** 117 | * The timeout value (in seconds) for the download operation. Default: 15.0. 118 | */ 119 | @property (assign, nonatomic) NSTimeInterval downloadTimeout; 120 | 121 | 122 | /** 123 | * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. 124 | */ 125 | @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; 126 | 127 | /** 128 | * Singleton method, returns the shared instance 129 | * 130 | * @return global shared instance of downloader class 131 | */ 132 | + (nonnull instancetype)sharedDownloader; 133 | 134 | /** 135 | * Set the default URL credential to be set for request operations. 136 | */ 137 | @property (strong, nonatomic, nullable) NSURLCredential *urlCredential; 138 | 139 | /** 140 | * Set username 141 | */ 142 | @property (strong, nonatomic, nullable) NSString *username; 143 | 144 | /** 145 | * Set password 146 | */ 147 | @property (strong, nonatomic, nullable) NSString *password; 148 | 149 | /** 150 | * Set filter to pick headers for downloading image HTTP request. 151 | * 152 | * This block will be invoked for each downloading image request, returned 153 | * NSDictionary will be used as headers in corresponding HTTP request. 154 | */ 155 | @property (nonatomic, copy, nullable) SDWebImageDownloaderHeadersFilterBlock headersFilter; 156 | 157 | /** 158 | * Creates an instance of a downloader with specified session configuration. 159 | * *Note*: `timeoutIntervalForRequest` is going to be overwritten. 160 | * @return new instance of downloader class 161 | */ 162 | - (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration NS_DESIGNATED_INITIALIZER; 163 | 164 | /** 165 | * Set a value for a HTTP header to be appended to each download HTTP request. 166 | * 167 | * @param value The value for the header field. Use `nil` value to remove the header. 168 | * @param field The name of the header field to set. 169 | */ 170 | - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field; 171 | 172 | /** 173 | * Returns the value of the specified HTTP header field. 174 | * 175 | * @return The value associated with the header field field, or `nil` if there is no corresponding header field. 176 | */ 177 | - (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field; 178 | 179 | /** 180 | * Sets a subclass of `SDWebImageDownloaderOperation` as the default 181 | * `NSOperation` to be used each time SDWebImage constructs a request 182 | * operation to download an image. 183 | * 184 | * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set 185 | * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. 186 | */ 187 | - (void)setOperationClass:(nullable Class)operationClass; 188 | 189 | /** 190 | * Creates a SDWebImageDownloader async downloader instance with a given URL 191 | * 192 | * The delegate will be informed when the image is finish downloaded or an error has happen. 193 | * 194 | * @see SDWebImageDownloaderDelegate 195 | * 196 | * @param url The URL to the image to download 197 | * @param options The options to be used for this download 198 | * @param progressBlock A block called repeatedly while the image is downloading 199 | * @note the progress block is executed on a background queue 200 | * @param completedBlock A block called once the download is completed. 201 | * If the download succeeded, the image parameter is set, in case of error, 202 | * error parameter is set with the error. The last parameter is always YES 203 | * if SDWebImageDownloaderProgressiveDownload isn't use. With the 204 | * SDWebImageDownloaderProgressiveDownload option, this block is called 205 | * repeatedly with the partial image object and the finished argument set to NO 206 | * before to be called a last time with the full image and finished argument 207 | * set to YES. In case of error, the finished argument is always YES. 208 | * 209 | * @return A token (SDWebImageDownloadToken) that can be passed to -cancel: to cancel this operation 210 | */ 211 | - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url 212 | options:(SDWebImageDownloaderOptions)options 213 | progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 214 | completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; 215 | 216 | /** 217 | * Cancels a download that was previously queued using -downloadImageWithURL:options:progress:completed: 218 | * 219 | * @param token The token received from -downloadImageWithURL:options:progress:completed: that should be canceled. 220 | */ 221 | - (void)cancel:(nullable SDWebImageDownloadToken *)token; 222 | 223 | /** 224 | * Sets the download queue suspension state 225 | */ 226 | - (void)setSuspended:(BOOL)suspended; 227 | 228 | /** 229 | * Cancels all download operations in the queue 230 | */ 231 | - (void)cancelAllDownloads; 232 | 233 | @end 234 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageDownloader.h" 11 | #import "SDWebImageOperation.h" 12 | 13 | extern NSString * _Nonnull const SDWebImageDownloadStartNotification; 14 | extern NSString * _Nonnull const SDWebImageDownloadReceiveResponseNotification; 15 | extern NSString * _Nonnull const SDWebImageDownloadStopNotification; 16 | extern NSString * _Nonnull const SDWebImageDownloadFinishNotification; 17 | 18 | 19 | 20 | /** 21 | Describes a downloader operation. If one wants to use a custom downloader op, it needs to inherit from `NSOperation` and conform to this protocol 22 | */ 23 | @protocol SDWebImageDownloaderOperationInterface 24 | 25 | - (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request 26 | inSession:(nullable NSURLSession *)session 27 | options:(SDWebImageDownloaderOptions)options; 28 | 29 | - (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 30 | completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; 31 | 32 | - (BOOL)shouldDecompressImages; 33 | - (void)setShouldDecompressImages:(BOOL)value; 34 | 35 | - (nullable NSURLCredential *)credential; 36 | - (void)setCredential:(nullable NSURLCredential *)value; 37 | 38 | @end 39 | 40 | 41 | @interface SDWebImageDownloaderOperation : NSOperation 42 | 43 | /** 44 | * The request used by the operation's task. 45 | */ 46 | @property (strong, nonatomic, readonly, nullable) NSURLRequest *request; 47 | 48 | /** 49 | * The operation's task 50 | */ 51 | @property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask; 52 | 53 | 54 | @property (assign, nonatomic) BOOL shouldDecompressImages; 55 | 56 | /** 57 | * Was used to determine whether the URL connection should consult the credential storage for authenticating the connection. 58 | * @deprecated Not used for a couple of versions 59 | */ 60 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage __deprecated_msg("Property deprecated. Does nothing. Kept only for backwards compatibility"); 61 | 62 | /** 63 | * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. 64 | * 65 | * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. 66 | */ 67 | @property (nonatomic, strong, nullable) NSURLCredential *credential; 68 | 69 | /** 70 | * The SDWebImageDownloaderOptions for the receiver. 71 | */ 72 | @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; 73 | 74 | /** 75 | * The expected size of data. 76 | */ 77 | @property (assign, nonatomic) NSInteger expectedSize; 78 | 79 | /** 80 | * The response returned by the operation's connection. 81 | */ 82 | @property (strong, nonatomic, nullable) NSURLResponse *response; 83 | 84 | /** 85 | * Initializes a `SDWebImageDownloaderOperation` object 86 | * 87 | * @see SDWebImageDownloaderOperation 88 | * 89 | * @param request the URL request 90 | * @param session the URL session in which this operation will run 91 | * @param options downloader options 92 | * 93 | * @return the initialized instance 94 | */ 95 | - (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request 96 | inSession:(nullable NSURLSession *)session 97 | options:(SDWebImageDownloaderOptions)options NS_DESIGNATED_INITIALIZER; 98 | 99 | /** 100 | * Adds handlers for progress and completion. Returns a tokent that can be passed to -cancel: to cancel this set of 101 | * callbacks. 102 | * 103 | * @param progressBlock the block executed when a new chunk of data arrives. 104 | * @note the progress block is executed on a background queue 105 | * @param completedBlock the block executed when the download is done. 106 | * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue 107 | * 108 | * @return the token to use to cancel this set of handlers 109 | */ 110 | - (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 111 | completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; 112 | 113 | /** 114 | * Cancels a set of callbacks. Once all callbacks are canceled, the operation is cancelled. 115 | * 116 | * @param token the token representing a set of callbacks to cancel 117 | * 118 | * @return YES if the operation was stopped because this was the last token to be canceled. NO otherwise. 119 | */ 120 | - (BOOL)cancel:(nullable id)token; 121 | 122 | @end 123 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/SDWebImageManager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | #import "SDWebImageOperation.h" 11 | #import "SDWebImageDownloader.h" 12 | #import "SDImageCache.h" 13 | 14 | typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { 15 | /** 16 | * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. 17 | * This flag disable this blacklisting. 18 | */ 19 | SDWebImageRetryFailed = 1 << 0, 20 | 21 | /** 22 | * By default, image downloads are started during UI interactions, this flags disable this feature, 23 | * leading to delayed download on UIScrollView deceleration for instance. 24 | */ 25 | SDWebImageLowPriority = 1 << 1, 26 | 27 | /** 28 | * This flag disables on-disk caching 29 | */ 30 | SDWebImageCacheMemoryOnly = 1 << 2, 31 | 32 | /** 33 | * This flag enables progressive download, the image is displayed progressively during download as a browser would do. 34 | * By default, the image is only displayed once completely downloaded. 35 | */ 36 | SDWebImageProgressiveDownload = 1 << 3, 37 | 38 | /** 39 | * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. 40 | * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. 41 | * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. 42 | * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. 43 | * 44 | * Use this flag only if you can't make your URLs static with embedded cache busting parameter. 45 | */ 46 | SDWebImageRefreshCached = 1 << 4, 47 | 48 | /** 49 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for 50 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled. 51 | */ 52 | SDWebImageContinueInBackground = 1 << 5, 53 | 54 | /** 55 | * Handles cookies stored in NSHTTPCookieStore by setting 56 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES; 57 | */ 58 | SDWebImageHandleCookies = 1 << 6, 59 | 60 | /** 61 | * Enable to allow untrusted SSL certificates. 62 | * Useful for testing purposes. Use with caution in production. 63 | */ 64 | SDWebImageAllowInvalidSSLCertificates = 1 << 7, 65 | 66 | /** 67 | * By default, images are loaded in the order in which they were queued. This flag moves them to 68 | * the front of the queue. 69 | */ 70 | SDWebImageHighPriority = 1 << 8, 71 | 72 | /** 73 | * By default, placeholder images are loaded while the image is loading. This flag will delay the loading 74 | * of the placeholder image until after the image has finished loading. 75 | */ 76 | SDWebImageDelayPlaceholder = 1 << 9, 77 | 78 | /** 79 | * We usually don't call transformDownloadedImage delegate method on animated images, 80 | * as most transformation code would mangle it. 81 | * Use this flag to transform them anyway. 82 | */ 83 | SDWebImageTransformAnimatedImage = 1 << 10, 84 | 85 | /** 86 | * By default, image is added to the imageView after download. But in some cases, we want to 87 | * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance) 88 | * Use this flag if you want to manually set the image in the completion when success 89 | */ 90 | SDWebImageAvoidAutoSetImage = 1 << 11, 91 | 92 | /** 93 | * By default, images are decoded respecting their original size. On iOS, this flag will scale down the 94 | * images to a size compatible with the constrained memory of devices. 95 | * If `SDWebImageProgressiveDownload` flag is set the scale down is deactivated. 96 | */ 97 | SDWebImageScaleDownLargeImages = 1 << 12 98 | }; 99 | 100 | typedef void(^SDExternalCompletionBlock)(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL); 101 | 102 | typedef void(^SDInternalCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL); 103 | 104 | typedef NSString * _Nullable (^SDWebImageCacheKeyFilterBlock)(NSURL * _Nullable url); 105 | 106 | 107 | @class SDWebImageManager; 108 | 109 | @protocol SDWebImageManagerDelegate 110 | 111 | @optional 112 | 113 | /** 114 | * Controls which image should be downloaded when the image is not found in the cache. 115 | * 116 | * @param imageManager The current `SDWebImageManager` 117 | * @param imageURL The url of the image to be downloaded 118 | * 119 | * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. 120 | */ 121 | - (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nullable NSURL *)imageURL; 122 | 123 | /** 124 | * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. 125 | * NOTE: This method is called from a global queue in order to not to block the main thread. 126 | * 127 | * @param imageManager The current `SDWebImageManager` 128 | * @param image The image to transform 129 | * @param imageURL The url of the image to transform 130 | * 131 | * @return The transformed image object. 132 | */ 133 | - (nullable UIImage *)imageManager:(nonnull SDWebImageManager *)imageManager transformDownloadedImage:(nullable UIImage *)image withURL:(nullable NSURL *)imageURL; 134 | 135 | @end 136 | 137 | /** 138 | * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. 139 | * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). 140 | * You can use this class directly to benefit from web image downloading with caching in another context than 141 | * a UIView. 142 | * 143 | * Here is a simple example of how to use SDWebImageManager: 144 | * 145 | * @code 146 | 147 | SDWebImageManager *manager = [SDWebImageManager sharedManager]; 148 | [manager loadImageWithURL:imageURL 149 | options:0 150 | progress:nil 151 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 152 | if (image) { 153 | // do something with image 154 | } 155 | }]; 156 | 157 | * @endcode 158 | */ 159 | @interface SDWebImageManager : NSObject 160 | 161 | @property (weak, nonatomic, nullable) id delegate; 162 | 163 | @property (strong, nonatomic, readonly, nullable) SDImageCache *imageCache; 164 | @property (strong, nonatomic, readonly, nullable) SDWebImageDownloader *imageDownloader; 165 | 166 | /** 167 | * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can 168 | * be used to remove dynamic part of an image URL. 169 | * 170 | * The following example sets a filter in the application delegate that will remove any query-string from the 171 | * URL before to use it as a cache key: 172 | * 173 | * @code 174 | 175 | [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { 176 | url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; 177 | return [url absoluteString]; 178 | }]; 179 | 180 | * @endcode 181 | */ 182 | @property (nonatomic, copy, nullable) SDWebImageCacheKeyFilterBlock cacheKeyFilter; 183 | 184 | /** 185 | * Returns global SDWebImageManager instance. 186 | * 187 | * @return SDWebImageManager shared instance 188 | */ 189 | + (nonnull instancetype)sharedManager; 190 | 191 | /** 192 | * Allows to specify instance of cache and image downloader used with image manager. 193 | * @return new instance of `SDWebImageManager` with specified cache and downloader. 194 | */ 195 | - (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader NS_DESIGNATED_INITIALIZER; 196 | 197 | /** 198 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise. 199 | * 200 | * @param url The URL to the image 201 | * @param options A mask to specify options to use for this request 202 | * @param progressBlock A block called while image is downloading 203 | * @note the progress block is executed on a background queue 204 | * @param completedBlock A block called when operation has been completed. 205 | * 206 | * This parameter is required. 207 | * 208 | * This block has no return value and takes the requested UIImage as first parameter and the NSData representation as second parameter. 209 | * In case of error the image parameter is nil and the third parameter may contain an NSError. 210 | * 211 | * The forth parameter is an `SDImageCacheType` enum indicating if the image was retrieved from the local cache 212 | * or from the memory cache or from the network. 213 | * 214 | * The fith parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is 215 | * downloading. This block is thus called repeatedly with a partial image. When image is fully downloaded, the 216 | * block is called a last time with the full image and the last parameter set to YES. 217 | * 218 | * The last parameter is the original image URL 219 | * 220 | * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation 221 | */ 222 | - (nullable id )loadImageWithURL:(nullable NSURL *)url 223 | options:(SDWebImageOptions)options 224 | progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 225 | completed:(nullable SDInternalCompletionBlock)completedBlock; 226 | 227 | /** 228 | * Saves image to cache for given URL 229 | * 230 | * @param image The image to cache 231 | * @param url The URL to the image 232 | * 233 | */ 234 | 235 | - (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url; 236 | 237 | /** 238 | * Cancel all current operations 239 | */ 240 | - (void)cancelAll; 241 | 242 | /** 243 | * Check one or more operations running 244 | */ 245 | - (BOOL)isRunning; 246 | 247 | /** 248 | * Async check if image has already been cached 249 | * 250 | * @param url image url 251 | * @param completionBlock the block to be executed when the check is finished 252 | * 253 | * @note the completion block is always executed on the main queue 254 | */ 255 | - (void)cachedImageExistsForURL:(nullable NSURL *)url 256 | completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock; 257 | 258 | /** 259 | * Async check if image has already been cached on disk only 260 | * 261 | * @param url image url 262 | * @param completionBlock the block to be executed when the check is finished 263 | * 264 | * @note the completion block is always executed on the main queue 265 | */ 266 | - (void)diskImageExistsForURL:(nullable NSURL *)url 267 | completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock; 268 | 269 | 270 | /** 271 | *Return the cache key for a given URL 272 | */ 273 | - (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url; 274 | 275 | @end 276 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/SDWebImageOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | 11 | @protocol SDWebImageOperation 12 | 13 | - (void)cancel; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/SDWebImagePrefetcher.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageManager.h" 11 | 12 | @class SDWebImagePrefetcher; 13 | 14 | @protocol SDWebImagePrefetcherDelegate 15 | 16 | @optional 17 | 18 | /** 19 | * Called when an image was prefetched. 20 | * 21 | * @param imagePrefetcher The current image prefetcher 22 | * @param imageURL The image url that was prefetched 23 | * @param finishedCount The total number of images that were prefetched (successful or not) 24 | * @param totalCount The total number of images that were to be prefetched 25 | */ 26 | - (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(nullable NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; 27 | 28 | /** 29 | * Called when all images are prefetched. 30 | * @param imagePrefetcher The current image prefetcher 31 | * @param totalCount The total number of images that were prefetched (whether successful or not) 32 | * @param skippedCount The total number of images that were skipped 33 | */ 34 | - (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; 35 | 36 | @end 37 | 38 | typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls); 39 | typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls); 40 | 41 | /** 42 | * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. 43 | */ 44 | @interface SDWebImagePrefetcher : NSObject 45 | 46 | /** 47 | * The web image manager 48 | */ 49 | @property (strong, nonatomic, readonly, nonnull) SDWebImageManager *manager; 50 | 51 | /** 52 | * Maximum number of URLs to prefetch at the same time. Defaults to 3. 53 | */ 54 | @property (nonatomic, assign) NSUInteger maxConcurrentDownloads; 55 | 56 | /** 57 | * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. 58 | */ 59 | @property (nonatomic, assign) SDWebImageOptions options; 60 | 61 | /** 62 | * Queue options for Prefetcher. Defaults to Main Queue. 63 | */ 64 | @property (nonatomic, assign, nonnull) dispatch_queue_t prefetcherQueue; 65 | 66 | @property (weak, nonatomic, nullable) id delegate; 67 | 68 | /** 69 | * Return the global image prefetcher instance. 70 | */ 71 | + (nonnull instancetype)sharedImagePrefetcher; 72 | 73 | /** 74 | * Allows you to instantiate a prefetcher with any arbitrary image manager. 75 | */ 76 | - (nonnull instancetype)initWithImageManager:(nonnull SDWebImageManager *)manager NS_DESIGNATED_INITIALIZER; 77 | 78 | /** 79 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 80 | * currently one image is downloaded at a time, 81 | * and skips images for failed downloads and proceed to the next image in the list. 82 | * Any previously-running prefetch operations are canceled. 83 | * 84 | * @param urls list of URLs to prefetch 85 | */ 86 | - (void)prefetchURLs:(nullable NSArray *)urls; 87 | 88 | /** 89 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 90 | * currently one image is downloaded at a time, 91 | * and skips images for failed downloads and proceed to the next image in the list. 92 | * Any previously-running prefetch operations are canceled. 93 | * 94 | * @param urls list of URLs to prefetch 95 | * @param progressBlock block to be called when progress updates; 96 | * first parameter is the number of completed (successful or not) requests, 97 | * second parameter is the total number of images originally requested to be prefetched 98 | * @param completionBlock block to be called when prefetching is completed 99 | * first param is the number of completed (successful or not) requests, 100 | * second parameter is the number of skipped requests 101 | */ 102 | - (void)prefetchURLs:(nullable NSArray *)urls 103 | progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock 104 | completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock; 105 | 106 | /** 107 | * Remove and cancel queued list 108 | */ 109 | - (void)cancelPrefetching; 110 | 111 | 112 | @end 113 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/SDWebImagePrefetcher.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImagePrefetcher.h" 10 | 11 | @interface SDWebImagePrefetcher () 12 | 13 | @property (strong, nonatomic, nonnull) SDWebImageManager *manager; 14 | @property (strong, nonatomic, nullable) NSArray *prefetchURLs; 15 | @property (assign, nonatomic) NSUInteger requestedCount; 16 | @property (assign, nonatomic) NSUInteger skippedCount; 17 | @property (assign, nonatomic) NSUInteger finishedCount; 18 | @property (assign, nonatomic) NSTimeInterval startedTime; 19 | @property (copy, nonatomic, nullable) SDWebImagePrefetcherCompletionBlock completionBlock; 20 | @property (copy, nonatomic, nullable) SDWebImagePrefetcherProgressBlock progressBlock; 21 | 22 | @end 23 | 24 | @implementation SDWebImagePrefetcher 25 | 26 | + (nonnull instancetype)sharedImagePrefetcher { 27 | static dispatch_once_t once; 28 | static id instance; 29 | dispatch_once(&once, ^{ 30 | instance = [self new]; 31 | }); 32 | return instance; 33 | } 34 | 35 | - (nonnull instancetype)init { 36 | return [self initWithImageManager:[SDWebImageManager new]]; 37 | } 38 | 39 | - (nonnull instancetype)initWithImageManager:(SDWebImageManager *)manager { 40 | if ((self = [super init])) { 41 | _manager = manager; 42 | _options = SDWebImageLowPriority; 43 | _prefetcherQueue = dispatch_get_main_queue(); 44 | self.maxConcurrentDownloads = 3; 45 | } 46 | return self; 47 | } 48 | 49 | - (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { 50 | self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; 51 | } 52 | 53 | - (NSUInteger)maxConcurrentDownloads { 54 | return self.manager.imageDownloader.maxConcurrentDownloads; 55 | } 56 | 57 | - (void)startPrefetchingAtIndex:(NSUInteger)index { 58 | if (index >= self.prefetchURLs.count) return; 59 | self.requestedCount++; 60 | [self.manager loadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 61 | if (!finished) return; 62 | self.finishedCount++; 63 | 64 | if (image) { 65 | if (self.progressBlock) { 66 | self.progressBlock(self.finishedCount,(self.prefetchURLs).count); 67 | } 68 | } 69 | else { 70 | if (self.progressBlock) { 71 | self.progressBlock(self.finishedCount,(self.prefetchURLs).count); 72 | } 73 | // Add last failed 74 | self.skippedCount++; 75 | } 76 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { 77 | [self.delegate imagePrefetcher:self 78 | didPrefetchURL:self.prefetchURLs[index] 79 | finishedCount:self.finishedCount 80 | totalCount:self.prefetchURLs.count 81 | ]; 82 | } 83 | if (self.prefetchURLs.count > self.requestedCount) { 84 | dispatch_async(self.prefetcherQueue, ^{ 85 | [self startPrefetchingAtIndex:self.requestedCount]; 86 | }); 87 | } else if (self.finishedCount == self.requestedCount) { 88 | [self reportStatus]; 89 | if (self.completionBlock) { 90 | self.completionBlock(self.finishedCount, self.skippedCount); 91 | self.completionBlock = nil; 92 | } 93 | self.progressBlock = nil; 94 | } 95 | }]; 96 | } 97 | 98 | - (void)reportStatus { 99 | NSUInteger total = (self.prefetchURLs).count; 100 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { 101 | [self.delegate imagePrefetcher:self 102 | didFinishWithTotalCount:(total - self.skippedCount) 103 | skippedCount:self.skippedCount 104 | ]; 105 | } 106 | } 107 | 108 | - (void)prefetchURLs:(nullable NSArray *)urls { 109 | [self prefetchURLs:urls progress:nil completed:nil]; 110 | } 111 | 112 | - (void)prefetchURLs:(nullable NSArray *)urls 113 | progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock 114 | completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock { 115 | [self cancelPrefetching]; // Prevent duplicate prefetch request 116 | self.startedTime = CFAbsoluteTimeGetCurrent(); 117 | self.prefetchURLs = urls; 118 | self.completionBlock = completionBlock; 119 | self.progressBlock = progressBlock; 120 | 121 | if (urls.count == 0) { 122 | if (completionBlock) { 123 | completionBlock(0,0); 124 | } 125 | } else { 126 | // Starts prefetching from the very first image on the list with the max allowed concurrency 127 | NSUInteger listCount = self.prefetchURLs.count; 128 | for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { 129 | [self startPrefetchingAtIndex:i]; 130 | } 131 | } 132 | } 133 | 134 | - (void)cancelPrefetching { 135 | self.prefetchURLs = nil; 136 | self.skippedCount = 0; 137 | self.requestedCount = 0; 138 | self.finishedCount = 0; 139 | [self.manager cancelAll]; 140 | } 141 | 142 | @end 143 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIButton+WebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | 11 | #if SD_UIKIT 12 | 13 | #import "SDWebImageManager.h" 14 | 15 | /** 16 | * Integrates SDWebImage async downloading and caching of remote images with UIButtonView. 17 | */ 18 | @interface UIButton (WebCache) 19 | 20 | /** 21 | * Get the current image URL. 22 | */ 23 | - (nullable NSURL *)sd_currentImageURL; 24 | 25 | #pragma mark - Image 26 | 27 | /** 28 | * Get the image URL for a control state. 29 | * 30 | * @param state Which state you want to know the URL for. The values are described in UIControlState. 31 | */ 32 | - (nullable NSURL *)sd_imageURLForState:(UIControlState)state; 33 | 34 | /** 35 | * Set the imageView `image` with an `url`. 36 | * 37 | * The download is asynchronous and cached. 38 | * 39 | * @param url The url for the image. 40 | * @param state The state that uses the specified title. The values are described in UIControlState. 41 | */ 42 | - (void)sd_setImageWithURL:(nullable NSURL *)url 43 | forState:(UIControlState)state; 44 | 45 | /** 46 | * Set the imageView `image` with an `url` and a placeholder. 47 | * 48 | * The download is asynchronous and cached. 49 | * 50 | * @param url The url for the image. 51 | * @param state The state that uses the specified title. The values are described in UIControlState. 52 | * @param placeholder The image to be set initially, until the image request finishes. 53 | * @see sd_setImageWithURL:placeholderImage:options: 54 | */ 55 | - (void)sd_setImageWithURL:(nullable NSURL *)url 56 | forState:(UIControlState)state 57 | placeholderImage:(nullable UIImage *)placeholder; 58 | 59 | /** 60 | * Set the imageView `image` with an `url`, placeholder and custom options. 61 | * 62 | * The download is asynchronous and cached. 63 | * 64 | * @param url The url for the image. 65 | * @param state The state that uses the specified title. The values are described in UIControlState. 66 | * @param placeholder The image to be set initially, until the image request finishes. 67 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 68 | */ 69 | - (void)sd_setImageWithURL:(nullable NSURL *)url 70 | forState:(UIControlState)state 71 | placeholderImage:(nullable UIImage *)placeholder 72 | options:(SDWebImageOptions)options; 73 | 74 | /** 75 | * Set the imageView `image` with an `url`. 76 | * 77 | * The download is asynchronous and cached. 78 | * 79 | * @param url The url for the image. 80 | * @param state The state that uses the specified title. The values are described in UIControlState. 81 | * @param completedBlock A block called when operation has been completed. This block has no return value 82 | * and takes the requested UIImage as first parameter. In case of error the image parameter 83 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 84 | * indicating if the image was retrieved from the local cache or from the network. 85 | * The fourth parameter is the original image url. 86 | */ 87 | - (void)sd_setImageWithURL:(nullable NSURL *)url 88 | forState:(UIControlState)state 89 | completed:(nullable SDExternalCompletionBlock)completedBlock; 90 | 91 | /** 92 | * Set the imageView `image` with an `url`, placeholder. 93 | * 94 | * The download is asynchronous and cached. 95 | * 96 | * @param url The url for the image. 97 | * @param state The state that uses the specified title. The values are described in UIControlState. 98 | * @param placeholder The image to be set initially, until the image request finishes. 99 | * @param completedBlock A block called when operation has been completed. This block has no return value 100 | * and takes the requested UIImage as first parameter. In case of error the image parameter 101 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 102 | * indicating if the image was retrieved from the local cache or from the network. 103 | * The fourth parameter is the original image url. 104 | */ 105 | - (void)sd_setImageWithURL:(nullable NSURL *)url 106 | forState:(UIControlState)state 107 | placeholderImage:(nullable UIImage *)placeholder 108 | completed:(nullable SDExternalCompletionBlock)completedBlock; 109 | 110 | /** 111 | * Set the imageView `image` with an `url`, placeholder and custom options. 112 | * 113 | * The download is asynchronous and cached. 114 | * 115 | * @param url The url for the image. 116 | * @param state The state that uses the specified title. The values are described in UIControlState. 117 | * @param placeholder The image to be set initially, until the image request finishes. 118 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 119 | * @param completedBlock A block called when operation has been completed. This block has no return value 120 | * and takes the requested UIImage as first parameter. In case of error the image parameter 121 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 122 | * indicating if the image was retrieved from the local cache or from the network. 123 | * The fourth parameter is the original image url. 124 | */ 125 | - (void)sd_setImageWithURL:(nullable NSURL *)url 126 | forState:(UIControlState)state 127 | placeholderImage:(nullable UIImage *)placeholder 128 | options:(SDWebImageOptions)options 129 | completed:(nullable SDExternalCompletionBlock)completedBlock; 130 | 131 | #pragma mark - Background image 132 | 133 | /** 134 | * Set the backgroundImageView `image` with an `url`. 135 | * 136 | * The download is asynchronous and cached. 137 | * 138 | * @param url The url for the image. 139 | * @param state The state that uses the specified title. The values are described in UIControlState. 140 | */ 141 | - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url 142 | forState:(UIControlState)state; 143 | 144 | /** 145 | * Set the backgroundImageView `image` with an `url` and a placeholder. 146 | * 147 | * The download is asynchronous and cached. 148 | * 149 | * @param url The url for the image. 150 | * @param state The state that uses the specified title. The values are described in UIControlState. 151 | * @param placeholder The image to be set initially, until the image request finishes. 152 | * @see sd_setImageWithURL:placeholderImage:options: 153 | */ 154 | - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url 155 | forState:(UIControlState)state 156 | placeholderImage:(nullable UIImage *)placeholder; 157 | 158 | /** 159 | * Set the backgroundImageView `image` with an `url`, placeholder and custom options. 160 | * 161 | * The download is asynchronous and cached. 162 | * 163 | * @param url The url for the image. 164 | * @param state The state that uses the specified title. The values are described in UIControlState. 165 | * @param placeholder The image to be set initially, until the image request finishes. 166 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 167 | */ 168 | - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url 169 | forState:(UIControlState)state 170 | placeholderImage:(nullable UIImage *)placeholder 171 | options:(SDWebImageOptions)options; 172 | 173 | /** 174 | * Set the backgroundImageView `image` with an `url`. 175 | * 176 | * The download is asynchronous and cached. 177 | * 178 | * @param url The url for the image. 179 | * @param state The state that uses the specified title. The values are described in UIControlState. 180 | * @param completedBlock A block called when operation has been completed. This block has no return value 181 | * and takes the requested UIImage as first parameter. In case of error the image parameter 182 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 183 | * indicating if the image was retrieved from the local cache or from the network. 184 | * The fourth parameter is the original image url. 185 | */ 186 | - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url 187 | forState:(UIControlState)state 188 | completed:(nullable SDExternalCompletionBlock)completedBlock; 189 | 190 | /** 191 | * Set the backgroundImageView `image` with an `url`, placeholder. 192 | * 193 | * The download is asynchronous and cached. 194 | * 195 | * @param url The url for the image. 196 | * @param state The state that uses the specified title. The values are described in UIControlState. 197 | * @param placeholder The image to be set initially, until the image request finishes. 198 | * @param completedBlock A block called when operation has been completed. This block has no return value 199 | * and takes the requested UIImage as first parameter. In case of error the image parameter 200 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 201 | * indicating if the image was retrieved from the local cache or from the network. 202 | * The fourth parameter is the original image url. 203 | */ 204 | - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url 205 | forState:(UIControlState)state 206 | placeholderImage:(nullable UIImage *)placeholder 207 | completed:(nullable SDExternalCompletionBlock)completedBlock; 208 | 209 | /** 210 | * Set the backgroundImageView `image` with an `url`, placeholder and custom options. 211 | * 212 | * The download is asynchronous and cached. 213 | * 214 | * @param url The url for the image. 215 | * @param placeholder The image to be set initially, until the image request finishes. 216 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 217 | * @param completedBlock A block called when operation has been completed. This block has no return value 218 | * and takes the requested UIImage as first parameter. In case of error the image parameter 219 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 220 | * indicating if the image was retrieved from the local cache or from the network. 221 | * The fourth parameter is the original image url. 222 | */ 223 | - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url 224 | forState:(UIControlState)state 225 | placeholderImage:(nullable UIImage *)placeholder 226 | options:(SDWebImageOptions)options 227 | completed:(nullable SDExternalCompletionBlock)completedBlock; 228 | 229 | #pragma mark - Cancel 230 | 231 | /** 232 | * Cancel the current image download 233 | */ 234 | - (void)sd_cancelImageLoadForState:(UIControlState)state; 235 | 236 | /** 237 | * Cancel the current backgroundImage download 238 | */ 239 | - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state; 240 | 241 | @end 242 | 243 | #endif 244 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIButton+WebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIButton+WebCache.h" 10 | 11 | #if SD_UIKIT 12 | 13 | #import "objc/runtime.h" 14 | #import "UIView+WebCacheOperation.h" 15 | #import "UIView+WebCache.h" 16 | 17 | static char imageURLStorageKey; 18 | 19 | typedef NSMutableDictionary SDStateImageURLDictionary; 20 | 21 | @implementation UIButton (WebCache) 22 | 23 | - (nullable NSURL *)sd_currentImageURL { 24 | NSURL *url = self.imageURLStorage[@(self.state)]; 25 | 26 | if (!url) { 27 | url = self.imageURLStorage[@(UIControlStateNormal)]; 28 | } 29 | 30 | return url; 31 | } 32 | 33 | - (nullable NSURL *)sd_imageURLForState:(UIControlState)state { 34 | return self.imageURLStorage[@(state)]; 35 | } 36 | 37 | #pragma mark - Image 38 | 39 | - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state { 40 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 41 | } 42 | 43 | - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder { 44 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 45 | } 46 | 47 | - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { 48 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 49 | } 50 | 51 | - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock { 52 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; 53 | } 54 | 55 | - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { 56 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; 57 | } 58 | 59 | - (void)sd_setImageWithURL:(nullable NSURL *)url 60 | forState:(UIControlState)state 61 | placeholderImage:(nullable UIImage *)placeholder 62 | options:(SDWebImageOptions)options 63 | completed:(nullable SDExternalCompletionBlock)completedBlock { 64 | if (!url) { 65 | [self.imageURLStorage removeObjectForKey:@(state)]; 66 | return; 67 | } 68 | 69 | self.imageURLStorage[@(state)] = url; 70 | 71 | __weak typeof(self)weakSelf = self; 72 | [self sd_internalSetImageWithURL:url 73 | placeholderImage:placeholder 74 | options:options 75 | operationKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)] 76 | setImageBlock:^(UIImage *image, NSData *imageData) { 77 | [weakSelf setImage:image forState:state]; 78 | } 79 | progress:nil 80 | completed:completedBlock]; 81 | } 82 | 83 | #pragma mark - Background image 84 | 85 | - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state { 86 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 87 | } 88 | 89 | - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder { 90 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 91 | } 92 | 93 | - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { 94 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 95 | } 96 | 97 | - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock { 98 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; 99 | } 100 | 101 | - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { 102 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; 103 | } 104 | 105 | - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url 106 | forState:(UIControlState)state 107 | placeholderImage:(nullable UIImage *)placeholder 108 | options:(SDWebImageOptions)options 109 | completed:(nullable SDExternalCompletionBlock)completedBlock { 110 | if (!url) { 111 | [self.imageURLStorage removeObjectForKey:@(state)]; 112 | return; 113 | } 114 | 115 | self.imageURLStorage[@(state)] = url; 116 | 117 | __weak typeof(self)weakSelf = self; 118 | [self sd_internalSetImageWithURL:url 119 | placeholderImage:placeholder 120 | options:options 121 | operationKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)] 122 | setImageBlock:^(UIImage *image, NSData *imageData) { 123 | [weakSelf setBackgroundImage:image forState:state]; 124 | } 125 | progress:nil 126 | completed:completedBlock]; 127 | } 128 | 129 | - (void)sd_setImageLoadOperation:(id)operation forState:(UIControlState)state { 130 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; 131 | } 132 | 133 | - (void)sd_cancelImageLoadForState:(UIControlState)state { 134 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; 135 | } 136 | 137 | - (void)sd_setBackgroundImageLoadOperation:(id)operation forState:(UIControlState)state { 138 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; 139 | } 140 | 141 | - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state { 142 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; 143 | } 144 | 145 | - (SDStateImageURLDictionary *)imageURLStorage { 146 | SDStateImageURLDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey); 147 | if (!storage) { 148 | storage = [NSMutableDictionary dictionary]; 149 | objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 150 | } 151 | 152 | return storage; 153 | } 154 | 155 | @end 156 | 157 | #endif 158 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIImage+GIF.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * (c) Laurin Brandner 5 | * 6 | * For the full copyright and license information, please view the LICENSE 7 | * file that was distributed with this source code. 8 | */ 9 | 10 | #import "SDWebImageCompat.h" 11 | 12 | @interface UIImage (GIF) 13 | 14 | /** 15 | * Compatibility method - creates an animated UIImage from an NSData, it will only contain the 1st frame image 16 | */ 17 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data; 18 | 19 | /** 20 | * Checks if an UIImage instance is a GIF. Will use the `images` array 21 | */ 22 | - (BOOL)isGIF; 23 | 24 | @end 25 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIImage+GIF.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * (c) Laurin Brandner 5 | * 6 | * For the full copyright and license information, please view the LICENSE 7 | * file that was distributed with this source code. 8 | */ 9 | 10 | #import "UIImage+GIF.h" 11 | #import 12 | #import "objc/runtime.h" 13 | #import "NSImage+WebCache.h" 14 | 15 | @implementation UIImage (GIF) 16 | 17 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data { 18 | if (!data) { 19 | return nil; 20 | } 21 | 22 | CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); 23 | 24 | size_t count = CGImageSourceGetCount(source); 25 | 26 | UIImage *staticImage; 27 | 28 | if (count <= 1) { 29 | staticImage = [[UIImage alloc] initWithData:data]; 30 | } else { 31 | // we will only retrieve the 1st frame. the full GIF support is available via the FLAnimatedImageView category. 32 | // this here is only code to allow drawing animated images as static ones 33 | #if SD_WATCH 34 | CGFloat scale = 1; 35 | scale = [WKInterfaceDevice currentDevice].screenScale; 36 | #elif SD_UIKIT 37 | CGFloat scale = 1; 38 | scale = [UIScreen mainScreen].scale; 39 | #endif 40 | 41 | CGImageRef CGImage = CGImageSourceCreateImageAtIndex(source, 0, NULL); 42 | #if SD_UIKIT || SD_WATCH 43 | UIImage *frameImage = [UIImage imageWithCGImage:CGImage scale:scale orientation:UIImageOrientationUp]; 44 | staticImage = [UIImage animatedImageWithImages:@[frameImage] duration:0.0f]; 45 | #elif SD_MAC 46 | staticImage = [[UIImage alloc] initWithCGImage:CGImage size:NSZeroSize]; 47 | #endif 48 | CGImageRelease(CGImage); 49 | } 50 | 51 | CFRelease(source); 52 | 53 | return staticImage; 54 | } 55 | 56 | - (BOOL)isGIF { 57 | return (self.images != nil); 58 | } 59 | 60 | @end 61 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIImage+MultiFormat.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | #import "NSData+ImageContentType.h" 11 | 12 | @interface UIImage (MultiFormat) 13 | 14 | + (nullable UIImage *)sd_imageWithData:(nullable NSData *)data; 15 | - (nullable NSData *)sd_imageData; 16 | - (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat; 17 | 18 | @end 19 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIImage+MultiFormat.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIImage+MultiFormat.h" 10 | #import "UIImage+GIF.h" 11 | #import "NSData+ImageContentType.h" 12 | #import 13 | 14 | #ifdef SD_WEBP 15 | #import "UIImage+WebP.h" 16 | #endif 17 | 18 | @implementation UIImage (MultiFormat) 19 | 20 | + (nullable UIImage *)sd_imageWithData:(nullable NSData *)data { 21 | if (!data) { 22 | return nil; 23 | } 24 | 25 | UIImage *image; 26 | SDImageFormat imageFormat = [NSData sd_imageFormatForImageData:data]; 27 | if (imageFormat == SDImageFormatGIF) { 28 | image = [UIImage sd_animatedGIFWithData:data]; 29 | } 30 | #ifdef SD_WEBP 31 | else if (imageFormat == SDImageFormatWebP) 32 | { 33 | image = [UIImage sd_imageWithWebPData:data]; 34 | } 35 | #endif 36 | else { 37 | image = [[UIImage alloc] initWithData:data]; 38 | #if SD_UIKIT || SD_WATCH 39 | UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data]; 40 | if (orientation != UIImageOrientationUp) { 41 | image = [UIImage imageWithCGImage:image.CGImage 42 | scale:image.scale 43 | orientation:orientation]; 44 | } 45 | #endif 46 | } 47 | 48 | 49 | return image; 50 | } 51 | 52 | #if SD_UIKIT || SD_WATCH 53 | +(UIImageOrientation)sd_imageOrientationFromImageData:(nonnull NSData *)imageData { 54 | UIImageOrientation result = UIImageOrientationUp; 55 | CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); 56 | if (imageSource) { 57 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); 58 | if (properties) { 59 | CFTypeRef val; 60 | int exifOrientation; 61 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); 62 | if (val) { 63 | CFNumberGetValue(val, kCFNumberIntType, &exifOrientation); 64 | result = [self sd_exifOrientationToiOSOrientation:exifOrientation]; 65 | } // else - if it's not set it remains at up 66 | CFRelease((CFTypeRef) properties); 67 | } else { 68 | //NSLog(@"NO PROPERTIES, FAIL"); 69 | } 70 | CFRelease(imageSource); 71 | } 72 | return result; 73 | } 74 | 75 | #pragma mark EXIF orientation tag converter 76 | // Convert an EXIF image orientation to an iOS one. 77 | // reference see here: http://sylvana.net/jpegcrop/exif_orientation.html 78 | + (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation { 79 | UIImageOrientation orientation = UIImageOrientationUp; 80 | switch (exifOrientation) { 81 | case 1: 82 | orientation = UIImageOrientationUp; 83 | break; 84 | 85 | case 3: 86 | orientation = UIImageOrientationDown; 87 | break; 88 | 89 | case 8: 90 | orientation = UIImageOrientationLeft; 91 | break; 92 | 93 | case 6: 94 | orientation = UIImageOrientationRight; 95 | break; 96 | 97 | case 2: 98 | orientation = UIImageOrientationUpMirrored; 99 | break; 100 | 101 | case 4: 102 | orientation = UIImageOrientationDownMirrored; 103 | break; 104 | 105 | case 5: 106 | orientation = UIImageOrientationLeftMirrored; 107 | break; 108 | 109 | case 7: 110 | orientation = UIImageOrientationRightMirrored; 111 | break; 112 | default: 113 | break; 114 | } 115 | return orientation; 116 | } 117 | #endif 118 | 119 | - (nullable NSData *)sd_imageData { 120 | return [self sd_imageDataAsFormat:SDImageFormatUndefined]; 121 | } 122 | 123 | - (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat { 124 | NSData *imageData = nil; 125 | if (self) { 126 | #if SD_UIKIT || SD_WATCH 127 | int alphaInfo = CGImageGetAlphaInfo(self.CGImage); 128 | BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone || 129 | alphaInfo == kCGImageAlphaNoneSkipFirst || 130 | alphaInfo == kCGImageAlphaNoneSkipLast); 131 | 132 | BOOL usePNG = hasAlpha; 133 | 134 | // the imageFormat param has priority here. But if the format is undefined, we relly on the alpha channel 135 | if (imageFormat != SDImageFormatUndefined) { 136 | usePNG = (imageFormat == SDImageFormatPNG); 137 | } 138 | 139 | if (usePNG) { 140 | imageData = UIImagePNGRepresentation(self); 141 | } else { 142 | imageData = UIImageJPEGRepresentation(self, (CGFloat)1.0); 143 | } 144 | #else 145 | NSBitmapImageFileType imageFileType = NSJPEGFileType; 146 | if (imageFormat == SDImageFormatGIF) { 147 | imageFileType = NSGIFFileType; 148 | } else if (imageFormat == SDImageFormatPNG) { 149 | imageFileType = NSPNGFileType; 150 | } 151 | 152 | imageData = [NSBitmapImageRep representationOfImageRepsInArray:self.representations 153 | usingType:imageFileType 154 | properties:@{}]; 155 | #endif 156 | } 157 | return imageData; 158 | } 159 | 160 | 161 | @end 162 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | 11 | #if SD_UIKIT 12 | 13 | #import "SDWebImageManager.h" 14 | 15 | /** 16 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state. 17 | */ 18 | @interface UIImageView (HighlightedWebCache) 19 | 20 | /** 21 | * Set the imageView `highlightedImage` with an `url`. 22 | * 23 | * The download is asynchronous and cached. 24 | * 25 | * @param url The url for the image. 26 | */ 27 | - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url; 28 | 29 | /** 30 | * Set the imageView `highlightedImage` with an `url` and custom options. 31 | * 32 | * The download is asynchronous and cached. 33 | * 34 | * @param url The url for the image. 35 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 36 | */ 37 | - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url 38 | options:(SDWebImageOptions)options; 39 | 40 | /** 41 | * Set the imageView `highlightedImage` with an `url`. 42 | * 43 | * The download is asynchronous and cached. 44 | * 45 | * @param url The url for the image. 46 | * @param completedBlock A block called when operation has been completed. This block has no return value 47 | * and takes the requested UIImage as first parameter. In case of error the image parameter 48 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 49 | * indicating if the image was retrieved from the local cache or from the network. 50 | * The fourth parameter is the original image url. 51 | */ 52 | - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url 53 | completed:(nullable SDExternalCompletionBlock)completedBlock; 54 | 55 | /** 56 | * Set the imageView `highlightedImage` with an `url` and custom options. 57 | * 58 | * The download is asynchronous and cached. 59 | * 60 | * @param url The url for the image. 61 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 62 | * @param completedBlock A block called when operation has been completed. This block has no return value 63 | * and takes the requested UIImage as first parameter. In case of error the image parameter 64 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 65 | * indicating if the image was retrieved from the local cache or from the network. 66 | * The fourth parameter is the original image url. 67 | */ 68 | - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url 69 | options:(SDWebImageOptions)options 70 | completed:(nullable SDExternalCompletionBlock)completedBlock; 71 | 72 | /** 73 | * Set the imageView `highlightedImage` with an `url` and custom options. 74 | * 75 | * The download is asynchronous and cached. 76 | * 77 | * @param url The url for the image. 78 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 79 | * @param progressBlock A block called while image is downloading 80 | * @note the progress block is executed on a background queue 81 | * @param completedBlock A block called when operation has been completed. This block has no return value 82 | * and takes the requested UIImage as first parameter. In case of error the image parameter 83 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 84 | * indicating if the image was retrieved from the local cache or from the network. 85 | * The fourth parameter is the original image url. 86 | */ 87 | - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url 88 | options:(SDWebImageOptions)options 89 | progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 90 | completed:(nullable SDExternalCompletionBlock)completedBlock; 91 | 92 | @end 93 | 94 | #endif 95 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIImageView+HighlightedWebCache.h" 10 | 11 | #if SD_UIKIT 12 | 13 | #import "UIView+WebCacheOperation.h" 14 | #import "UIView+WebCache.h" 15 | 16 | @implementation UIImageView (HighlightedWebCache) 17 | 18 | - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url { 19 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; 20 | } 21 | 22 | - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options { 23 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; 24 | } 25 | 26 | - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { 27 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock]; 28 | } 29 | 30 | - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { 31 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock]; 32 | } 33 | 34 | - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url 35 | options:(SDWebImageOptions)options 36 | progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 37 | completed:(nullable SDExternalCompletionBlock)completedBlock { 38 | __weak typeof(self)weakSelf = self; 39 | [self sd_internalSetImageWithURL:url 40 | placeholderImage:nil 41 | options:options 42 | operationKey:@"UIImageViewImageOperationHighlighted" 43 | setImageBlock:^(UIImage *image, NSData *imageData) { 44 | weakSelf.highlightedImage = image; 45 | } 46 | progress:progressBlock 47 | completed:completedBlock]; 48 | } 49 | 50 | @end 51 | 52 | #endif 53 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIImageView+WebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | 11 | #if SD_UIKIT || SD_MAC 12 | 13 | #import "SDWebImageManager.h" 14 | 15 | /** 16 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView. 17 | * 18 | * Usage with a UITableViewCell sub-class: 19 | * 20 | * @code 21 | 22 | #import 23 | 24 | ... 25 | 26 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 27 | { 28 | static NSString *MyIdentifier = @"MyIdentifier"; 29 | 30 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 31 | 32 | if (cell == nil) { 33 | cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] 34 | autorelease]; 35 | } 36 | 37 | // Here we use the provided sd_setImageWithURL: method to load the web image 38 | // Ensure you use a placeholder image otherwise cells will be initialized with no image 39 | [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] 40 | placeholderImage:[UIImage imageNamed:@"placeholder"]]; 41 | 42 | cell.textLabel.text = @"My Text"; 43 | return cell; 44 | } 45 | 46 | * @endcode 47 | */ 48 | @interface UIImageView (WebCache) 49 | 50 | /** 51 | * Set the imageView `image` with an `url`. 52 | * 53 | * The download is asynchronous and cached. 54 | * 55 | * @param url The url for the image. 56 | */ 57 | - (void)sd_setImageWithURL:(nullable NSURL *)url; 58 | 59 | /** 60 | * Set the imageView `image` with an `url` and a placeholder. 61 | * 62 | * The download is asynchronous and cached. 63 | * 64 | * @param url The url for the image. 65 | * @param placeholder The image to be set initially, until the image request finishes. 66 | * @see sd_setImageWithURL:placeholderImage:options: 67 | */ 68 | - (void)sd_setImageWithURL:(nullable NSURL *)url 69 | placeholderImage:(nullable UIImage *)placeholder; 70 | 71 | /** 72 | * Set the imageView `image` with an `url`, placeholder and custom options. 73 | * 74 | * The download is asynchronous and cached. 75 | * 76 | * @param url The url for the image. 77 | * @param placeholder The image to be set initially, until the image request finishes. 78 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 79 | */ 80 | - (void)sd_setImageWithURL:(nullable NSURL *)url 81 | placeholderImage:(nullable UIImage *)placeholder 82 | options:(SDWebImageOptions)options; 83 | 84 | /** 85 | * Set the imageView `image` with an `url`. 86 | * 87 | * The download is asynchronous and cached. 88 | * 89 | * @param url The url for the image. 90 | * @param completedBlock A block called when operation has been completed. This block has no return value 91 | * and takes the requested UIImage as first parameter. In case of error the image parameter 92 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 93 | * indicating if the image was retrieved from the local cache or from the network. 94 | * The fourth parameter is the original image url. 95 | */ 96 | - (void)sd_setImageWithURL:(nullable NSURL *)url 97 | completed:(nullable SDExternalCompletionBlock)completedBlock; 98 | 99 | /** 100 | * Set the imageView `image` with an `url`, placeholder. 101 | * 102 | * The download is asynchronous and cached. 103 | * 104 | * @param url The url for the image. 105 | * @param placeholder The image to be set initially, until the image request finishes. 106 | * @param completedBlock A block called when operation has been completed. This block has no return value 107 | * and takes the requested UIImage as first parameter. In case of error the image parameter 108 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 109 | * indicating if the image was retrieved from the local cache or from the network. 110 | * The fourth parameter is the original image url. 111 | */ 112 | - (void)sd_setImageWithURL:(nullable NSURL *)url 113 | placeholderImage:(nullable UIImage *)placeholder 114 | completed:(nullable SDExternalCompletionBlock)completedBlock; 115 | 116 | /** 117 | * Set the imageView `image` with an `url`, placeholder and custom options. 118 | * 119 | * The download is asynchronous and cached. 120 | * 121 | * @param url The url for the image. 122 | * @param placeholder The image to be set initially, until the image request finishes. 123 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 124 | * @param completedBlock A block called when operation has been completed. This block has no return value 125 | * and takes the requested UIImage as first parameter. In case of error the image parameter 126 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 127 | * indicating if the image was retrieved from the local cache or from the network. 128 | * The fourth parameter is the original image url. 129 | */ 130 | - (void)sd_setImageWithURL:(nullable NSURL *)url 131 | placeholderImage:(nullable UIImage *)placeholder 132 | options:(SDWebImageOptions)options 133 | completed:(nullable SDExternalCompletionBlock)completedBlock; 134 | 135 | /** 136 | * Set the imageView `image` with an `url`, placeholder and custom options. 137 | * 138 | * The download is asynchronous and cached. 139 | * 140 | * @param url The url for the image. 141 | * @param placeholder The image to be set initially, until the image request finishes. 142 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 143 | * @param progressBlock A block called while image is downloading 144 | * @note the progress block is executed on a background queue 145 | * @param completedBlock A block called when operation has been completed. This block has no return value 146 | * and takes the requested UIImage as first parameter. In case of error the image parameter 147 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 148 | * indicating if the image was retrieved from the local cache or from the network. 149 | * The fourth parameter is the original image url. 150 | */ 151 | - (void)sd_setImageWithURL:(nullable NSURL *)url 152 | placeholderImage:(nullable UIImage *)placeholder 153 | options:(SDWebImageOptions)options 154 | progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 155 | completed:(nullable SDExternalCompletionBlock)completedBlock; 156 | 157 | /** 158 | * Set the imageView `image` with an `url` and optionally a placeholder image. 159 | * 160 | * The download is asynchronous and cached. 161 | * 162 | * @param url The url for the image. 163 | * @param placeholder The image to be set initially, until the image request finishes. 164 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 165 | * @param progressBlock A block called while image is downloading 166 | * @note the progress block is executed on a background queue 167 | * @param completedBlock A block called when operation has been completed. This block has no return value 168 | * and takes the requested UIImage as first parameter. In case of error the image parameter 169 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 170 | * indicating if the image was retrieved from the local cache or from the network. 171 | * The fourth parameter is the original image url. 172 | */ 173 | - (void)sd_setImageWithPreviousCachedImageWithURL:(nullable NSURL *)url 174 | placeholderImage:(nullable UIImage *)placeholder 175 | options:(SDWebImageOptions)options 176 | progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 177 | completed:(nullable SDExternalCompletionBlock)completedBlock; 178 | 179 | #if SD_UIKIT 180 | 181 | #pragma mark - Animation of multiple images 182 | 183 | /** 184 | * Download an array of images and starts them in an animation loop 185 | * 186 | * @param arrayOfURLs An array of NSURL 187 | */ 188 | - (void)sd_setAnimationImagesWithURLs:(nonnull NSArray *)arrayOfURLs; 189 | 190 | - (void)sd_cancelCurrentAnimationImagesLoad; 191 | 192 | #endif 193 | 194 | @end 195 | 196 | #endif 197 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIImageView+WebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIImageView+WebCache.h" 10 | 11 | #if SD_UIKIT || SD_MAC 12 | 13 | #import "objc/runtime.h" 14 | #import "UIView+WebCacheOperation.h" 15 | #import "UIView+WebCache.h" 16 | 17 | @implementation UIImageView (WebCache) 18 | 19 | - (void)sd_setImageWithURL:(nullable NSURL *)url { 20 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; 21 | } 22 | 23 | - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder { 24 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; 25 | } 26 | 27 | - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { 28 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; 29 | } 30 | 31 | - (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { 32 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; 33 | } 34 | 35 | - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { 36 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; 37 | } 38 | 39 | - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { 40 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; 41 | } 42 | 43 | - (void)sd_setImageWithURL:(nullable NSURL *)url 44 | placeholderImage:(nullable UIImage *)placeholder 45 | options:(SDWebImageOptions)options 46 | progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 47 | completed:(nullable SDExternalCompletionBlock)completedBlock { 48 | [self sd_internalSetImageWithURL:url 49 | placeholderImage:placeholder 50 | options:options 51 | operationKey:nil 52 | setImageBlock:nil 53 | progress:progressBlock 54 | completed:completedBlock]; 55 | } 56 | 57 | - (void)sd_setImageWithPreviousCachedImageWithURL:(nullable NSURL *)url 58 | placeholderImage:(nullable UIImage *)placeholder 59 | options:(SDWebImageOptions)options 60 | progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 61 | completed:(nullable SDExternalCompletionBlock)completedBlock { 62 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; 63 | UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:key]; 64 | 65 | [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; 66 | } 67 | 68 | #if SD_UIKIT 69 | 70 | #pragma mark - Animation of multiple images 71 | 72 | - (void)sd_setAnimationImagesWithURLs:(nonnull NSArray *)arrayOfURLs { 73 | [self sd_cancelCurrentAnimationImagesLoad]; 74 | __weak __typeof(self)wself = self; 75 | 76 | NSMutableArray> *operationsArray = [[NSMutableArray alloc] init]; 77 | 78 | for (NSURL *logoImageURL in arrayOfURLs) { 79 | id operation = [SDWebImageManager.sharedManager loadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 80 | if (!wself) return; 81 | dispatch_main_async_safe(^{ 82 | __strong UIImageView *sself = wself; 83 | [sself stopAnimating]; 84 | if (sself && image) { 85 | NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; 86 | if (!currentImages) { 87 | currentImages = [[NSMutableArray alloc] init]; 88 | } 89 | [currentImages addObject:image]; 90 | 91 | sself.animationImages = currentImages; 92 | [sself setNeedsLayout]; 93 | } 94 | [sself startAnimating]; 95 | }); 96 | }]; 97 | [operationsArray addObject:operation]; 98 | } 99 | 100 | [self sd_setImageLoadOperation:[operationsArray copy] forKey:@"UIImageViewAnimationImages"]; 101 | } 102 | 103 | - (void)sd_cancelCurrentAnimationImagesLoad { 104 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"]; 105 | } 106 | #endif 107 | 108 | @end 109 | 110 | #endif 111 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIView+WebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | 11 | #if SD_UIKIT || SD_MAC 12 | 13 | #import "SDWebImageManager.h" 14 | 15 | typedef void(^SDSetImageBlock)(UIImage * _Nullable image, NSData * _Nullable imageData); 16 | 17 | @interface UIView (WebCache) 18 | 19 | /** 20 | * Get the current image URL. 21 | * 22 | * Note that because of the limitations of categories this property can get out of sync 23 | * if you use setImage: directly. 24 | */ 25 | - (nullable NSURL *)sd_imageURL; 26 | 27 | /** 28 | * Set the imageView `image` with an `url` and optionally a placeholder image. 29 | * 30 | * The download is asynchronous and cached. 31 | * 32 | * @param url The url for the image. 33 | * @param placeholder The image to be set initially, until the image request finishes. 34 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 35 | * @param operationKey A string to be used as the operation key. If nil, will use the class name 36 | * @param setImageBlock Block used for custom set image code 37 | * @param progressBlock A block called while image is downloading 38 | * @note the progress block is executed on a background queue 39 | * @param completedBlock A block called when operation has been completed. This block has no return value 40 | * and takes the requested UIImage as first parameter. In case of error the image parameter 41 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 42 | * indicating if the image was retrieved from the local cache or from the network. 43 | * The fourth parameter is the original image url. 44 | */ 45 | - (void)sd_internalSetImageWithURL:(nullable NSURL *)url 46 | placeholderImage:(nullable UIImage *)placeholder 47 | options:(SDWebImageOptions)options 48 | operationKey:(nullable NSString *)operationKey 49 | setImageBlock:(nullable SDSetImageBlock)setImageBlock 50 | progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 51 | completed:(nullable SDExternalCompletionBlock)completedBlock; 52 | 53 | /** 54 | * Cancel the current download 55 | */ 56 | - (void)sd_cancelCurrentImageLoad; 57 | 58 | #if SD_UIKIT 59 | 60 | #pragma mark - Activity indicator 61 | 62 | /** 63 | * Show activity UIActivityIndicatorView 64 | */ 65 | - (void)sd_setShowActivityIndicatorView:(BOOL)show; 66 | 67 | /** 68 | * set desired UIActivityIndicatorViewStyle 69 | * 70 | * @param style The style of the UIActivityIndicatorView 71 | */ 72 | - (void)sd_setIndicatorStyle:(UIActivityIndicatorViewStyle)style; 73 | 74 | - (BOOL)sd_showActivityIndicatorView; 75 | - (void)sd_addActivityIndicator; 76 | - (void)sd_removeActivityIndicator; 77 | 78 | #endif 79 | 80 | @end 81 | 82 | #endif 83 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIView+WebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIView+WebCache.h" 10 | 11 | #if SD_UIKIT || SD_MAC 12 | 13 | #import "objc/runtime.h" 14 | #import "UIView+WebCacheOperation.h" 15 | 16 | static char imageURLKey; 17 | 18 | #if SD_UIKIT 19 | static char TAG_ACTIVITY_INDICATOR; 20 | static char TAG_ACTIVITY_STYLE; 21 | #endif 22 | static char TAG_ACTIVITY_SHOW; 23 | 24 | @implementation UIView (WebCache) 25 | 26 | - (nullable NSURL *)sd_imageURL { 27 | return objc_getAssociatedObject(self, &imageURLKey); 28 | } 29 | 30 | - (void)sd_internalSetImageWithURL:(nullable NSURL *)url 31 | placeholderImage:(nullable UIImage *)placeholder 32 | options:(SDWebImageOptions)options 33 | operationKey:(nullable NSString *)operationKey 34 | setImageBlock:(nullable SDSetImageBlock)setImageBlock 35 | progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 36 | completed:(nullable SDExternalCompletionBlock)completedBlock { 37 | NSString *validOperationKey = operationKey ?: NSStringFromClass([self class]); 38 | [self sd_cancelImageLoadOperationWithKey:validOperationKey]; 39 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 40 | 41 | if (!(options & SDWebImageDelayPlaceholder)) { 42 | dispatch_main_async_safe(^{ 43 | [self sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock]; 44 | }); 45 | } 46 | 47 | if (url) { 48 | // check if activityView is enabled or not 49 | if ([self sd_showActivityIndicatorView]) { 50 | [self sd_addActivityIndicator]; 51 | } 52 | 53 | __weak __typeof(self)wself = self; 54 | id operation = [SDWebImageManager.sharedManager loadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 55 | __strong __typeof (wself) sself = wself; 56 | [sself sd_removeActivityIndicator]; 57 | if (!sself) { 58 | return; 59 | } 60 | dispatch_main_async_safe(^{ 61 | if (!sself) { 62 | return; 63 | } 64 | if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) { 65 | completedBlock(image, error, cacheType, url); 66 | return; 67 | } else if (image) { 68 | [sself sd_setImage:image imageData:data basedOnClassOrViaCustomSetImageBlock:setImageBlock]; 69 | [sself sd_setNeedsLayout]; 70 | } else { 71 | if ((options & SDWebImageDelayPlaceholder)) { 72 | [sself sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock]; 73 | [sself sd_setNeedsLayout]; 74 | } 75 | } 76 | if (completedBlock && finished) { 77 | completedBlock(image, error, cacheType, url); 78 | } 79 | }); 80 | }]; 81 | [self sd_setImageLoadOperation:operation forKey:validOperationKey]; 82 | } else { 83 | dispatch_main_async_safe(^{ 84 | [self sd_removeActivityIndicator]; 85 | if (completedBlock) { 86 | NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 87 | completedBlock(nil, error, SDImageCacheTypeNone, url); 88 | } 89 | }); 90 | } 91 | } 92 | 93 | - (void)sd_cancelCurrentImageLoad { 94 | [self sd_cancelImageLoadOperationWithKey:NSStringFromClass([self class])]; 95 | } 96 | 97 | - (void)sd_setImage:(UIImage *)image imageData:(NSData *)imageData basedOnClassOrViaCustomSetImageBlock:(SDSetImageBlock)setImageBlock { 98 | if (setImageBlock) { 99 | setImageBlock(image, imageData); 100 | return; 101 | } 102 | 103 | #if SD_UIKIT || SD_MAC 104 | if ([self isKindOfClass:[UIImageView class]]) { 105 | UIImageView *imageView = (UIImageView *)self; 106 | imageView.image = image; 107 | } 108 | #endif 109 | 110 | #if SD_UIKIT 111 | if ([self isKindOfClass:[UIButton class]]) { 112 | UIButton *button = (UIButton *)self; 113 | [button setImage:image forState:UIControlStateNormal]; 114 | } 115 | #endif 116 | } 117 | 118 | - (void)sd_setNeedsLayout { 119 | #if SD_UIKIT 120 | [self setNeedsLayout]; 121 | #elif SD_MAC 122 | [self setNeedsLayout:YES]; 123 | #endif 124 | } 125 | 126 | #pragma mark - Activity indicator 127 | 128 | #pragma mark - 129 | #if SD_UIKIT 130 | - (UIActivityIndicatorView *)activityIndicator { 131 | return (UIActivityIndicatorView *)objc_getAssociatedObject(self, &TAG_ACTIVITY_INDICATOR); 132 | } 133 | 134 | - (void)setActivityIndicator:(UIActivityIndicatorView *)activityIndicator { 135 | objc_setAssociatedObject(self, &TAG_ACTIVITY_INDICATOR, activityIndicator, OBJC_ASSOCIATION_RETAIN); 136 | } 137 | #endif 138 | 139 | - (void)sd_setShowActivityIndicatorView:(BOOL)show { 140 | objc_setAssociatedObject(self, &TAG_ACTIVITY_SHOW, @(show), OBJC_ASSOCIATION_RETAIN); 141 | } 142 | 143 | - (BOOL)sd_showActivityIndicatorView { 144 | return [objc_getAssociatedObject(self, &TAG_ACTIVITY_SHOW) boolValue]; 145 | } 146 | 147 | #if SD_UIKIT 148 | - (void)sd_setIndicatorStyle:(UIActivityIndicatorViewStyle)style{ 149 | objc_setAssociatedObject(self, &TAG_ACTIVITY_STYLE, [NSNumber numberWithInt:style], OBJC_ASSOCIATION_RETAIN); 150 | } 151 | 152 | - (int)sd_getIndicatorStyle{ 153 | return [objc_getAssociatedObject(self, &TAG_ACTIVITY_STYLE) intValue]; 154 | } 155 | #endif 156 | 157 | - (void)sd_addActivityIndicator { 158 | #if SD_UIKIT 159 | if (!self.activityIndicator) { 160 | self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:[self sd_getIndicatorStyle]]; 161 | self.activityIndicator.translatesAutoresizingMaskIntoConstraints = NO; 162 | 163 | dispatch_main_async_safe(^{ 164 | [self addSubview:self.activityIndicator]; 165 | 166 | [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityIndicator 167 | attribute:NSLayoutAttributeCenterX 168 | relatedBy:NSLayoutRelationEqual 169 | toItem:self 170 | attribute:NSLayoutAttributeCenterX 171 | multiplier:1.0 172 | constant:0.0]]; 173 | [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityIndicator 174 | attribute:NSLayoutAttributeCenterY 175 | relatedBy:NSLayoutRelationEqual 176 | toItem:self 177 | attribute:NSLayoutAttributeCenterY 178 | multiplier:1.0 179 | constant:0.0]]; 180 | }); 181 | } 182 | 183 | dispatch_main_async_safe(^{ 184 | [self.activityIndicator startAnimating]; 185 | }); 186 | #endif 187 | } 188 | 189 | - (void)sd_removeActivityIndicator { 190 | #if SD_UIKIT 191 | if (self.activityIndicator) { 192 | [self.activityIndicator removeFromSuperview]; 193 | self.activityIndicator = nil; 194 | } 195 | #endif 196 | } 197 | 198 | @end 199 | 200 | #endif 201 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIView+WebCacheOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | 11 | #if SD_UIKIT || SD_MAC 12 | 13 | #import "SDWebImageManager.h" 14 | 15 | @interface UIView (WebCacheOperation) 16 | 17 | /** 18 | * Set the image load operation (storage in a UIView based dictionary) 19 | * 20 | * @param operation the operation 21 | * @param key key for storing the operation 22 | */ 23 | - (void)sd_setImageLoadOperation:(nullable id)operation forKey:(nullable NSString *)key; 24 | 25 | /** 26 | * Cancel all operations for the current UIView and key 27 | * 28 | * @param key key for identifying the operations 29 | */ 30 | - (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key; 31 | 32 | /** 33 | * Just remove the operations corresponding to the current UIView and key without cancelling them 34 | * 35 | * @param key key for identifying the operations 36 | */ 37 | - (void)sd_removeImageLoadOperationWithKey:(nullable NSString *)key; 38 | 39 | @end 40 | 41 | #endif 42 | -------------------------------------------------------------------------------- /个人主页demo/SDWebImage/SDWebImage/UIView+WebCacheOperation.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIView+WebCacheOperation.h" 10 | 11 | #if SD_UIKIT || SD_MAC 12 | 13 | #import "objc/runtime.h" 14 | 15 | static char loadOperationKey; 16 | 17 | typedef NSMutableDictionary SDOperationsDictionary; 18 | 19 | @implementation UIView (WebCacheOperation) 20 | 21 | - (SDOperationsDictionary *)operationDictionary { 22 | SDOperationsDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey); 23 | if (operations) { 24 | return operations; 25 | } 26 | operations = [NSMutableDictionary dictionary]; 27 | objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 28 | return operations; 29 | } 30 | 31 | - (void)sd_setImageLoadOperation:(nullable id)operation forKey:(nullable NSString *)key { 32 | if (key) { 33 | [self sd_cancelImageLoadOperationWithKey:key]; 34 | if (operation) { 35 | SDOperationsDictionary *operationDictionary = [self operationDictionary]; 36 | operationDictionary[key] = operation; 37 | } 38 | } 39 | } 40 | 41 | - (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key { 42 | // Cancel in progress downloader from queue 43 | SDOperationsDictionary *operationDictionary = [self operationDictionary]; 44 | id operations = operationDictionary[key]; 45 | if (operations) { 46 | if ([operations isKindOfClass:[NSArray class]]) { 47 | for (id operation in operations) { 48 | if (operation) { 49 | [operation cancel]; 50 | } 51 | } 52 | } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){ 53 | [(id) operations cancel]; 54 | } 55 | [operationDictionary removeObjectForKey:key]; 56 | } 57 | } 58 | 59 | - (void)sd_removeImageLoadOperationWithKey:(nullable NSString *)key { 60 | if (key) { 61 | SDOperationsDictionary *operationDictionary = [self operationDictionary]; 62 | [operationDictionary removeObjectForKey:key]; 63 | } 64 | } 65 | 66 | @end 67 | 68 | #endif 69 | -------------------------------------------------------------------------------- /个人主页demo/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // 个人主页demo 4 | // 5 | // Created by hyw on 2018/11/14. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /个人主页demo/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // 个人主页demo 4 | // 5 | // Created by hyw on 2018/11/14. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | #import "PersonalCenterViewController.h" 11 | 12 | @interface ViewController () 13 | @property (weak, nonatomic) IBOutlet UISwitch *enlargeSwitch; 14 | 15 | @end 16 | 17 | @implementation ViewController 18 | 19 | - (void)viewDidLoad { 20 | [super viewDidLoad]; 21 | // Do any additional setup after loading the view, typically from a nib. 22 | } 23 | 24 | - (IBAction)intoCenterAction:(id)sender { 25 | PersonalCenterViewController *personalCenterVC = [[PersonalCenterViewController alloc]init]; 26 | personalCenterVC.isEnlarge = self.enlargeSwitch.on; 27 | personalCenterVC.selectedIndex = 0; 28 | [self.navigationController pushViewController:personalCenterVC animated:YES]; 29 | } 30 | 31 | - (void)didReceiveMemoryWarning { 32 | [super didReceiveMemoryWarning]; 33 | // Dispose of any resources that can be recreated. 34 | } 35 | 36 | 37 | @end 38 | -------------------------------------------------------------------------------- /个人主页demo/YWPerson/CenterTouchTableView.h: -------------------------------------------------------------------------------- 1 | // 2 | // CenterTouchTableView.h 3 | // 个人主页demo 4 | // 5 | // Created by hyw on 2018/11/14. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface CenterTouchTableView : UITableView 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /个人主页demo/YWPerson/CenterTouchTableView.m: -------------------------------------------------------------------------------- 1 | // 2 | // CenterTouchTableView.m 3 | // 个人主页demo 4 | // 5 | // Created by hyw on 2018/11/14. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import "CenterTouchTableView.h" 10 | 11 | @implementation CenterTouchTableView 12 | //允许接收多个手势 13 | - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { 14 | return YES; 15 | } 16 | 17 | 18 | ////代理方法 19 | //- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { 20 | // // 点击的view的类名 21 | // NSLog(@"%@", NSStringFromClass([touch.view class])); 22 | // // 点击了tableViewCell,view的类名为UITableViewCellContentView,则不接收Touch点击事件 23 | // if ([NSStringFromClass([touch.view class]) isEqualToString:@"CycScrollView"]) { 24 | // return NO; 25 | // } 26 | // return YES; 27 | //} 28 | 29 | @end 30 | -------------------------------------------------------------------------------- /个人主页demo/YWPerson/HMSegmentedControl.h: -------------------------------------------------------------------------------- 1 | // 2 | // HMSegmentedControl.h 3 | // HMSegmentedControl 4 | // 5 | // Created by Hesham Abd-Elmegid on 23/12/12. 6 | // Copyright (c) 2012-2015 Hesham Abd-Elmegid. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class HMSegmentedControl; 12 | 13 | typedef void (^IndexChangeBlock)(NSInteger index); 14 | typedef NSAttributedString *(^HMTitleFormatterBlock)(HMSegmentedControl *segmentedControl, NSString *title, NSUInteger index, BOOL selected); 15 | 16 | typedef NS_ENUM(NSInteger, HMSegmentedControlSelectionStyle) { 17 | HMSegmentedControlSelectionStyleTextWidthStripe, // Indicator width will only be as big as the text width 18 | HMSegmentedControlSelectionStyleFullWidthStripe, // Indicator width will fill the whole segment 19 | HMSegmentedControlSelectionStyleBox, // A rectangle that covers the whole segment 20 | HMSegmentedControlSelectionStyleArrow // An arrow in the middle of the segment pointing up or down depending on `HMSegmentedControlSelectionIndicatorLocation` 21 | }; 22 | 23 | typedef NS_ENUM(NSInteger, HMSegmentedControlSelectionIndicatorLocation) { 24 | HMSegmentedControlSelectionIndicatorLocationUp, 25 | HMSegmentedControlSelectionIndicatorLocationDown, 26 | HMSegmentedControlSelectionIndicatorLocationNone // No selection indicator 27 | }; 28 | 29 | typedef NS_ENUM(NSInteger, HMSegmentedControlSegmentWidthStyle) { 30 | HMSegmentedControlSegmentWidthStyleFixed, // Segment width is fixed 31 | HMSegmentedControlSegmentWidthStyleDynamic, // Segment width will only be as big as the text width (including inset) 32 | }; 33 | 34 | typedef NS_OPTIONS(NSInteger, HMSegmentedControlBorderType) { 35 | HMSegmentedControlBorderTypeNone = 0, 36 | HMSegmentedControlBorderTypeTop = (1 << 0), 37 | HMSegmentedControlBorderTypeLeft = (1 << 1), 38 | HMSegmentedControlBorderTypeBottom = (1 << 2), 39 | HMSegmentedControlBorderTypeRight = (1 << 3) 40 | }; 41 | 42 | enum { 43 | HMSegmentedControlNoSegment = -1 // Segment index for no selected segment 44 | }; 45 | 46 | typedef NS_ENUM(NSInteger, HMSegmentedControlType) { 47 | HMSegmentedControlTypeText, 48 | HMSegmentedControlTypeImages, 49 | HMSegmentedControlTypeTextImages 50 | }; 51 | 52 | typedef NS_ENUM(NSInteger, HMSegmentedControlImagePosition) { 53 | HMSegmentedControlImagePositionBehindText, 54 | HMSegmentedControlImagePositionLeftOfText, 55 | HMSegmentedControlImagePositionRightOfText, 56 | HMSegmentedControlImagePositionAboveText, 57 | HMSegmentedControlImagePositionBelowText 58 | }; 59 | 60 | @interface HMSegmentedControl : UIControl 61 | 62 | @property (nonatomic, strong) NSArray *sectionTitles; 63 | @property (nonatomic, strong) NSArray *sectionImages; 64 | @property (nonatomic, strong) NSArray *sectionSelectedImages; 65 | 66 | /** 67 | Provide a block to be executed when selected index is changed. 68 | 69 | Alternativly, you could use `addTarget:action:forControlEvents:` 70 | */ 71 | @property (nonatomic, copy) IndexChangeBlock indexChangeBlock; 72 | 73 | /** 74 | Used to apply custom text styling to titles when set. 75 | 76 | When this block is set, no additional styling is applied to the `NSAttributedString` object returned from this block. 77 | */ 78 | @property (nonatomic, copy) HMTitleFormatterBlock titleFormatter; 79 | 80 | /** 81 | Text attributes to apply to item title text. 82 | */ 83 | @property (nonatomic, strong) NSDictionary *titleTextAttributes UI_APPEARANCE_SELECTOR; 84 | 85 | /* 86 | Text attributes to apply to selected item title text. 87 | 88 | Attributes not set in this dictionary are inherited from `titleTextAttributes`. 89 | */ 90 | @property (nonatomic, strong) NSDictionary *selectedTitleTextAttributes UI_APPEARANCE_SELECTOR; 91 | 92 | /** 93 | Segmented control background color. 94 | 95 | Default is `[UIColor whiteColor]` 96 | */ 97 | @property (nonatomic, strong) UIColor *backgroundColor UI_APPEARANCE_SELECTOR; 98 | 99 | /** 100 | Color for the selection indicator stripe 101 | 102 | Default is `R:52, G:181, B:229` 103 | */ 104 | @property (nonatomic, strong) UIColor *selectionIndicatorColor UI_APPEARANCE_SELECTOR; 105 | 106 | /** 107 | Color for the selection indicator box 108 | 109 | Default is selectionIndicatorColor 110 | */ 111 | @property (nonatomic, strong) UIColor *selectionIndicatorBoxColor UI_APPEARANCE_SELECTOR; 112 | 113 | /** 114 | Color for the vertical divider between segments. 115 | 116 | Default is `[UIColor blackColor]` 117 | */ 118 | @property (nonatomic, strong) UIColor *verticalDividerColor UI_APPEARANCE_SELECTOR; 119 | 120 | /** 121 | Opacity for the seletion indicator box. 122 | 123 | Default is `0.2f` 124 | */ 125 | @property (nonatomic) CGFloat selectionIndicatorBoxOpacity; 126 | 127 | /** 128 | Width the vertical divider between segments that is added when `verticalDividerEnabled` is set to YES. 129 | 130 | Default is `1.0f` 131 | */ 132 | @property (nonatomic, assign) CGFloat verticalDividerWidth; 133 | 134 | /** 135 | Specifies the style of the control 136 | 137 | Default is `HMSegmentedControlTypeText` 138 | */ 139 | @property (nonatomic, assign) HMSegmentedControlType type; 140 | 141 | /** 142 | Specifies the style of the selection indicator. 143 | 144 | Default is `HMSegmentedControlSelectionStyleTextWidthStripe` 145 | */ 146 | @property (nonatomic, assign) HMSegmentedControlSelectionStyle selectionStyle; 147 | 148 | /** 149 | Specifies the style of the segment's width. 150 | 151 | Default is `HMSegmentedControlSegmentWidthStyleFixed` 152 | */ 153 | @property (nonatomic, assign) HMSegmentedControlSegmentWidthStyle segmentWidthStyle; 154 | 155 | /** 156 | Specifies the location of the selection indicator. 157 | 158 | Default is `HMSegmentedControlSelectionIndicatorLocationUp` 159 | */ 160 | @property (nonatomic, assign) HMSegmentedControlSelectionIndicatorLocation selectionIndicatorLocation; 161 | 162 | /* 163 | Specifies the border type. 164 | 165 | Default is `HMSegmentedControlBorderTypeNone` 166 | */ 167 | @property (nonatomic, assign) HMSegmentedControlBorderType borderType; 168 | 169 | /** 170 | Specifies the image position relative to the text. Only applicable for HMSegmentedControlTypeTextImages 171 | 172 | Default is `HMSegmentedControlImagePositionBehindText` 173 | */ 174 | @property (nonatomic) HMSegmentedControlImagePosition imagePosition; 175 | 176 | /** 177 | Specifies the distance between the text and the image. Only applicable for HMSegmentedControlTypeTextImages 178 | 179 | Default is `0,0` 180 | */ 181 | @property (nonatomic) CGFloat textImageSpacing; 182 | 183 | /** 184 | Specifies the border color. 185 | 186 | Default is `[UIColor blackColor]` 187 | */ 188 | @property (nonatomic, strong) UIColor *borderColor; 189 | 190 | /** 191 | Specifies the border width. 192 | 193 | Default is `1.0f` 194 | */ 195 | @property (nonatomic, assign) CGFloat borderWidth; 196 | 197 | /** 198 | Default is YES. Set to NO to deny scrolling by dragging the scrollView by the user. 199 | */ 200 | @property(nonatomic, getter = isUserDraggable) BOOL userDraggable; 201 | 202 | /** 203 | Default is YES. Set to NO to deny any touch events by the user. 204 | */ 205 | @property(nonatomic, getter = isTouchEnabled) BOOL touchEnabled; 206 | 207 | /** 208 | Default is NO. Set to YES to show a vertical divider between the segments. 209 | */ 210 | @property(nonatomic, getter = isVerticalDividerEnabled) BOOL verticalDividerEnabled; 211 | 212 | @property (nonatomic, getter=shouldStretchSegmentsToScreenSize) BOOL stretchSegmentsToScreenSize; 213 | 214 | /** 215 | Index of the currently selected segment. 216 | */ 217 | @property (nonatomic, assign) NSInteger selectedSegmentIndex; 218 | 219 | /** 220 | Height of the selection indicator. Only effective when `HMSegmentedControlSelectionStyle` is either `HMSegmentedControlSelectionStyleTextWidthStripe` or `HMSegmentedControlSelectionStyleFullWidthStripe`. 221 | 222 | Default is 5.0 223 | */ 224 | @property (nonatomic, readwrite) CGFloat selectionIndicatorHeight; 225 | 226 | /** 227 | Edge insets for the selection indicator. 228 | NOTE: This does not affect the bounding box of HMSegmentedControlSelectionStyleBox 229 | 230 | When HMSegmentedControlSelectionIndicatorLocationUp is selected, bottom edge insets are not used 231 | 232 | When HMSegmentedControlSelectionIndicatorLocationDown is selected, top edge insets are not used 233 | 234 | Defaults are top: 0.0f 235 | left: 0.0f 236 | bottom: 0.0f 237 | right: 0.0f 238 | */ 239 | @property (nonatomic, readwrite) UIEdgeInsets selectionIndicatorEdgeInsets; 240 | 241 | /** 242 | Inset left and right edges of segments. 243 | 244 | Default is UIEdgeInsetsMake(0, 5, 0, 5) 245 | */ 246 | @property (nonatomic, readwrite) UIEdgeInsets segmentEdgeInset; 247 | 248 | @property (nonatomic, readwrite) UIEdgeInsets enlargeEdgeInset; 249 | 250 | /** 251 | Default is YES. Set to NO to disable animation during user selection. 252 | */ 253 | @property (nonatomic) BOOL shouldAnimateUserSelection; 254 | 255 | - (id)initWithSectionTitles:(NSArray *)sectiontitles; 256 | - (id)initWithSectionImages:(NSArray *)sectionImages sectionSelectedImages:(NSArray *)sectionSelectedImages; 257 | - (instancetype)initWithSectionImages:(NSArray *)sectionImages sectionSelectedImages:(NSArray *)sectionSelectedImages titlesForSections:(NSArray *)sectiontitles; 258 | - (void)setSelectedSegmentIndex:(NSUInteger)index animated:(BOOL)animated; 259 | - (void)setIndexChangeBlock:(IndexChangeBlock)indexChangeBlock; 260 | - (void)setTitleFormatter:(HMTitleFormatterBlock)titleFormatter; 261 | 262 | @end 263 | -------------------------------------------------------------------------------- /个人主页demo/YWPerson/SegmentView.h: -------------------------------------------------------------------------------- 1 | // 2 | // SegmentView.h 3 | // 个人主页demo 4 | // 5 | // Created by hyw on 2018/11/14. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface SegmentView : UIView 12 | - (instancetype)initWithFrame:(CGRect)frame controllers:(NSArray *)controllers titleArray:(NSArray *)titleArray parentController:(UIViewController *)parentController; 13 | @end 14 | -------------------------------------------------------------------------------- /个人主页demo/YWPerson/SegmentView.m: -------------------------------------------------------------------------------- 1 | // 2 | // SegmentView.m 3 | // 个人主页demo 4 | // 5 | // Created by hyw on 2018/11/14. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import "SegmentView.h" 10 | #import "HMSegmentedControl.h" 11 | 12 | 13 | 14 | #define kWidth self.frame.size.width 15 | #define kHeight self.frame.size.height 16 | 17 | @interface SegmentView () 18 | @property(nonatomic, strong)HMSegmentedControl *segmentedControl; 19 | @property (nonatomic, strong) UIScrollView *contentScrollView; 20 | @property (nonatomic,strong) NSArray *ChildViewControllers; 21 | @end 22 | 23 | @implementation SegmentView 24 | 25 | #pragma mark - Life 26 | - (instancetype)initWithFrame:(CGRect)frame controllers:(NSArray *)controllers titleArray:(NSArray *)titleArray parentController:(UIViewController *)parentController { 27 | if ( self = [super initWithFrame:frame]) { 28 | self.frame = frame; 29 | self.ChildViewControllers = controllers; 30 | self.segmentedControl = [[HMSegmentedControl alloc] init]; 31 | self.segmentedControl.sectionTitles = @[@"详情",@"进度"]; 32 | self.segmentedControl.selectedSegmentIndex = 0; 33 | self.segmentedControl.backgroundColor = [UIColor whiteColor];//设定背景色 34 | self.segmentedControl.selectionIndicatorColor = UIColorFromRGB(0xD37EFA);//设定线条的颜色 35 | 36 | self.segmentedControl.titleTextAttributes = @{NSForegroundColorAttributeName:UIColorFromRGB(0x343434), 37 | NSFontAttributeName:[UIFont systemFontOfSize:14]};//设定title的颜色和字体 38 | self.segmentedControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName:UIColorFromRGB(0x343434), 39 | NSFontAttributeName:[UIFont systemFontOfSize:14]};//设定选中title时的颜色和字体 40 | 41 | self.segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;//设定线条的位置 42 | // self.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleBox;//设定线条的宽度 43 | // segmentedControl1.segmentEdgeInset = UIEdgeInsetsMake(0, 10, 0, 10); //设置每个title上下左右间距 44 | self.segmentedControl.selectionIndicatorHeight = 3.f;//设定线条的高度 45 | self.segmentedControl.frame = CGRectMake(0, 0, kWidth, SegmentHeaderViewHeight); 46 | [self addSubview:self.segmentedControl]; 47 | 48 | [self.segmentedControl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged]; 49 | 50 | // NSLog(@"segmentedControl高度 ==%f",self.segmentedControl.frame.size.height); 51 | 52 | self.contentScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, SegmentHeaderViewHeight, kWidth, kHeight - SegmentHeaderViewHeight)]; 53 | self.contentScrollView.contentSize = CGSizeMake(kWidth * controllers.count, 0); 54 | self.contentScrollView.delegate = self; 55 | self.contentScrollView.showsHorizontalScrollIndicator = NO; 56 | self.contentScrollView.pagingEnabled = YES; 57 | self.contentScrollView.bounces = NO; 58 | [self addSubview:self.contentScrollView]; 59 | 60 | // NSLog(@"contentScrollView高度 ==%f",self.contentScrollView.frame.size.height); 61 | 62 | UIViewController *vc = [self.ChildViewControllers firstObject]; 63 | vc.view.frame = CGRectMake(0, 0, kWidth, kHeight - SegmentHeaderViewHeight); 64 | [self.contentScrollView addSubview:vc.view]; 65 | 66 | 67 | 68 | } 69 | return self; 70 | } 71 | 72 | #pragma mark - HMSegmentedControl 73 | - (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl { 74 | [self.contentScrollView setContentOffset:CGPointMake(kWidth *(segmentedControl.selectedSegmentIndex), 0) animated:YES]; 75 | 76 | } 77 | 78 | #pragma mark - UIScrollViewDelegate 79 | //增加分页视图左右滑动和外界tableView上下滑动互斥处理 80 | - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { 81 | [[NSNotificationCenter defaultCenter] postNotificationName:IsEnablePersonalCenterVCMainTableViewScroll object:nil userInfo:@{@"canScroll":@"0"}]; 82 | } 83 | 84 | - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { 85 | [[NSNotificationCenter defaultCenter] postNotificationName:IsEnablePersonalCenterVCMainTableViewScroll object:nil userInfo:@{@"canScroll":@"1"}]; 86 | } 87 | 88 | - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { 89 | [self scrollViewDidEndScrollingAnimation:scrollView]; 90 | 91 | } 92 | 93 | -(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { 94 | if (scrollView == self.contentScrollView) { 95 | // 获得当前需要显示的子控制器的索引 96 | NSUInteger index = scrollView.contentOffset.x / scrollView.frame.size.width; 97 | _segmentedControl.selectedSegmentIndex = index; 98 | UIViewController *vc = self.ChildViewControllers[index]; 99 | // 如果子控制器的view已经在上面,就直接返回 100 | if (vc.view.superview) return; 101 | // 添加 102 | CGFloat vcW = scrollView.frame.size.width; 103 | CGFloat vcH = kHeight - SegmentHeaderViewHeight; 104 | CGFloat vcX = index * vcW; 105 | CGFloat vcY = 0; 106 | vc.view.frame = CGRectMake(vcX, vcY, vcW, vcH); 107 | [scrollView addSubview:vc.view]; 108 | } 109 | 110 | } 111 | 112 | @end 113 | -------------------------------------------------------------------------------- /个人主页demo/YWPerson/SegmentViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // SegmentViewController.h 3 | // PersonalCenter 4 | // 5 | // Created by Arch on 2017/6/16. 6 | // Copyright © 2017年 mint_bin. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface SegmentViewController : UIViewController 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /个人主页demo/YWPerson/SegmentViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // SegmentViewController.m 3 | // PersonalCenter 4 | // 5 | // Created by Arch on 2017/6/16. 6 | // Copyright © 2017年 mint_bin. All rights reserved. 7 | // 8 | 9 | #import "SegmentViewController.h" 10 | @interface SegmentViewController () 11 | @property (nonatomic, strong) UIScrollView *scrollView; 12 | @property (nonatomic, assign) BOOL canScroll; 13 | @end 14 | 15 | @implementation SegmentViewController 16 | #pragma mark - Life Cycle 17 | - (void)viewDidLoad { 18 | [super viewDidLoad]; 19 | //子控制器视图到达顶部的通知 20 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:@"goTop" object:nil]; 21 | //子控制器视图离开顶部的通知 22 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:@"leaveTop" object:nil]; 23 | //返回顶部的通知 24 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:SegementViewChildVCBackToTop object:nil]; 25 | } 26 | 27 | - (void)viewDidAppear:(BOOL)animated { 28 | [super viewDidAppear:animated]; 29 | if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { 30 | self.navigationController.interactivePopGestureRecognizer.delegate = self; 31 | } 32 | } 33 | 34 | - (void)dealloc { 35 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 36 | } 37 | 38 | #pragma mark - Private Methods 39 | - (void)acceptMsg:(NSNotification *)notification { 40 | NSString *notificationName = notification.name; 41 | if ([notificationName isEqualToString:@"goTop"]) { 42 | NSDictionary *userInfo = notification.userInfo; 43 | NSString *canScroll = userInfo[@"canScroll"]; 44 | if ([canScroll isEqualToString:@"1"]) { 45 | self.canScroll = YES; 46 | self.scrollView.showsVerticalScrollIndicator = YES; 47 | } else { 48 | self.canScroll = NO; 49 | } 50 | } else if ([notificationName isEqualToString:@"leaveTop"]){ 51 | self.canScroll = NO; 52 | self.scrollView.contentOffset = CGPointZero; 53 | self.scrollView.showsVerticalScrollIndicator = NO; 54 | }else if ([notificationName isEqualToString:SegementViewChildVCBackToTop]) { 55 | [self.scrollView setContentOffset:CGPointZero]; 56 | } 57 | } 58 | 59 | #pragma mark UIScrollViewDelegate 60 | - (void)scrollViewDidScroll:(UIScrollView *)scrollView { 61 | if (!self.canScroll) { 62 | [scrollView setContentOffset:CGPointZero]; 63 | } 64 | CGFloat offsetY = scrollView.contentOffset.y; 65 | if (offsetY <= 0) { 66 | [[NSNotificationCenter defaultCenter] postNotificationName:@"leaveTop" object:nil userInfo:@{@"canScroll":@"1"}]; 67 | } 68 | self.scrollView = scrollView; 69 | } 70 | 71 | 72 | 73 | @end 74 | -------------------------------------------------------------------------------- /个人主页demo/YWPerson/UIView+Extension.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIView+Extension.h 3 | // 黑马微博2期 4 | // 5 | // Created by apple on 14-10-7. 6 | // Copyright (c) 2014年 heima. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface UIView (Extension) 12 | @property (nonatomic, assign) CGFloat x; 13 | @property (nonatomic, assign) CGFloat y; 14 | @property (nonatomic, assign) CGFloat centerX; 15 | @property (nonatomic, assign) CGFloat centerY; 16 | @property (nonatomic, assign) CGFloat width; 17 | @property (nonatomic, assign) CGFloat height; 18 | @property (nonatomic, assign) CGSize size; 19 | @property (nonatomic, assign) CGPoint origin; 20 | 21 | @property (assign, nonatomic) CGFloat mj_maxY; 22 | @property (assign, nonatomic) CGFloat mj_maxX; 23 | @end 24 | -------------------------------------------------------------------------------- /个人主页demo/YWPerson/UIView+Extension.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIView+Extension.m 3 | // 黑马微博2期 4 | // 5 | // Created by apple on 14-10-7. 6 | // Copyright (c) 2014年 heima. All rights reserved. 7 | // 8 | 9 | #import "UIView+Extension.h" 10 | 11 | @implementation UIView (Extension) 12 | 13 | - (void)setX:(CGFloat)x 14 | { 15 | CGRect frame = self.frame; 16 | frame.origin.x = x; 17 | self.frame = frame; 18 | } 19 | 20 | - (void)setY:(CGFloat)y 21 | { 22 | CGRect frame = self.frame; 23 | frame.origin.y = y; 24 | self.frame = frame; 25 | } 26 | 27 | - (CGFloat)x 28 | { 29 | return self.frame.origin.x; 30 | } 31 | 32 | - (CGFloat)y 33 | { 34 | return self.frame.origin.y; 35 | } 36 | 37 | - (void)setCenterX:(CGFloat)centerX 38 | { 39 | CGPoint center = self.center; 40 | center.x = centerX; 41 | self.center = center; 42 | } 43 | 44 | - (CGFloat)centerX 45 | { 46 | return self.center.x; 47 | } 48 | 49 | - (void)setCenterY:(CGFloat)centerY 50 | { 51 | CGPoint center = self.center; 52 | center.y = centerY; 53 | self.center = center; 54 | } 55 | 56 | - (CGFloat)centerY 57 | { 58 | return self.center.y; 59 | } 60 | 61 | - (void)setWidth:(CGFloat)width 62 | { 63 | if (isnan(width)) { 64 | return; 65 | } 66 | CGRect frame = self.frame; 67 | frame.size.width = width; 68 | self.frame = frame; 69 | } 70 | 71 | - (void)setHeight:(CGFloat)height 72 | { 73 | CGRect frame = self.frame; 74 | frame.size.height = height; 75 | self.frame = frame; 76 | } 77 | 78 | - (CGFloat)height 79 | { 80 | return self.frame.size.height; 81 | } 82 | 83 | - (CGFloat)width 84 | { 85 | return self.frame.size.width; 86 | } 87 | 88 | - (void)setSize:(CGSize)size 89 | { 90 | CGRect frame = self.frame; 91 | frame.size = size; 92 | self.frame = frame; 93 | } 94 | 95 | - (CGSize)size 96 | { 97 | return self.frame.size; 98 | } 99 | 100 | - (void)setOrigin:(CGPoint)origin 101 | { 102 | CGRect frame = self.frame; 103 | frame.origin = origin; 104 | self.frame = frame; 105 | } 106 | 107 | - (CGPoint)origin 108 | { 109 | return self.frame.origin; 110 | } 111 | 112 | -(CGFloat)mj_maxY 113 | { 114 | return self.frame.origin.y+self.frame.size.height; 115 | 116 | } 117 | -(CGFloat)mj_maxX 118 | { 119 | return self.frame.origin.x+self.frame.size.width; 120 | } 121 | @end 122 | -------------------------------------------------------------------------------- /个人主页demo/YWPerson/YWPageHeadView.h: -------------------------------------------------------------------------------- 1 | // 2 | // YWPageHeadView.h 3 | // 新个人主页 4 | // 5 | // Created by hyw on 2018/11/19. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | //上下移动block y<0为上移,y>0为下移 12 | typedef void(^moveDirectionDownOrUpBlock)(CGFloat y); 13 | @interface YWPageHeadView : UIView 14 | @property (nonatomic,weak) UIView *parentView; //手势移动的对比view 15 | @property (nonatomic,weak) UIScrollView *parentScrollView; //外部联动视图 16 | @property (nonatomic,weak) UIScrollView *chidlScrollView; //内部联动视图 17 | 18 | 19 | @property (nonatomic,copy) moveDirectionDownOrUpBlock moveDirectionDownOrUpBlock; 20 | @end 21 | -------------------------------------------------------------------------------- /个人主页demo/YWPerson/YWPageHeadView.m: -------------------------------------------------------------------------------- 1 | // 2 | // YWPageHeadView.m 3 | // 新个人主页 4 | // 5 | // Created by hyw on 2018/11/19. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import "YWPageHeadView.h" 10 | 11 | @interface YWPageHeadView () 12 | @property(nonatomic,assign)BOOL isMoveDownUp; //是否上下滑动 13 | 14 | 15 | @end 16 | 17 | @implementation YWPageHeadView 18 | 19 | - (instancetype)init 20 | { 21 | self = [super init]; 22 | if (self) { 23 | [self setUpView]; 24 | } 25 | return self; 26 | } 27 | 28 | #pragma mark - UI 29 | - (void)setUpView{ 30 | UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)]; 31 | panGesture.delegate = self; 32 | [self addGestureRecognizer:panGesture]; 33 | 34 | 35 | } 36 | 37 | ////1返回值是返回是否生效。此方法在gesture recognizer视图转出UIGestureRecognizerStatePossible状态时调用,如果返回NO,则转换到UIGestureRecognizerStateFailed;如果返回YES,则继续识别触摸序列 38 | // 给加的手势设置代理, 并实现此协议方法 39 | - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { 40 | if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) { 41 | self.chidlScrollView.scrollEnabled = YES; 42 | self.parentScrollView.scrollEnabled = YES; 43 | // self.isMoveDownUp = YES; 44 | UIPanGestureRecognizer *pan = (UIPanGestureRecognizer *)gestureRecognizer; 45 | CGPoint pos = [pan velocityInView:self.parentView]; 46 | CGFloat absX = fabs(pos.x); 47 | CGFloat absY = fabs(pos.y); 48 | 49 | NSLog(@"translation === %@",NSStringFromCGPoint(pos)); 50 | if (absX > absY ) { 51 | self.isMoveDownUp = NO; 52 | self.parentScrollView.scrollEnabled = NO; 53 | self.chidlScrollView.scrollEnabled = YES; 54 | if (pos.x<0) { 55 | NSLog(@"向左滑动"); 56 | }else{ 57 | NSLog(@"向右滑动"); 58 | } 59 | 60 | return YES; 61 | } else if (absY >= absX) { 62 | // self.isMoveDownUp = YES; 63 | self.chidlScrollView.scrollEnabled = NO; 64 | self.parentScrollView.scrollEnabled = YES; 65 | if (pos.y<0) { 66 | NSLog(@"向上滑动"); 67 | }else{ 68 | NSLog(@"向下滑动"); 69 | }} 70 | return YES; 71 | } 72 | 73 | return NO; 74 | } 75 | 76 | 77 | //2 78 | //此方法返回YES时,手势事件会一直往下传递(允许多手势触发),不论当前层次是否对该事件进行响应。 79 | -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { 80 | // if (self.isMoveDownUp) { 81 | return YES; 82 | // } 83 | // return self.isMoveDownUp; 84 | } 85 | 86 | 87 | - (void)panAction:(UIPanGestureRecognizer *)recognizer { 88 | 89 | if (recognizer.state == UIGestureRecognizerStateBegan){ 90 | // self.chidlScrollView.scrollEnabled = YES; 91 | // self.parentScrollView.scrollEnabled = YES; 92 | }else if (recognizer.state == UIGestureRecognizerStateChanged) { 93 | // [self commitTranslation:[recognizer translationInView:self.parentView]]; 94 | }else if (recognizer.state == UIGestureRecognizerStateEnded){ 95 | self.chidlScrollView.scrollEnabled = YES; 96 | self.parentScrollView.scrollEnabled = YES; 97 | } 98 | // NSLog(@"recognizer.state === %ld",(long)recognizer.state); 99 | } 100 | 101 | /** 102 | * 判断手势方向 103 | * 104 | * @param translation translation description 105 | */ 106 | - (void)commitTranslation:(CGPoint)translation 107 | { 108 | 109 | CGFloat absX = fabs(translation.x); 110 | CGFloat absY = fabs(translation.y); 111 | 112 | // 设置滑动有效距离 113 | // if (MAX(absX, absY) < 10) 114 | // return; 115 | 116 | // NSLog(@"translation === %@",NSStringFromCGPoint(translation)); 117 | if (absX > absY ) { 118 | 119 | 120 | if (translation.x<0) { 121 | NSLog(@"左移"); 122 | //向左滑动 123 | self.parentScrollView.scrollEnabled = NO; 124 | self.chidlScrollView.scrollEnabled = YES; 125 | }else{ 126 | 127 | //向右滑动 128 | NSLog(@"右移"); 129 | self.parentScrollView.scrollEnabled = NO; 130 | self.chidlScrollView.scrollEnabled = YES; 131 | } 132 | 133 | 134 | } else if (absY > absX) { 135 | self.chidlScrollView.scrollEnabled = NO; 136 | self.parentScrollView.scrollEnabled = YES; 137 | // self.chidlScrollView.scrollEnabled = NO; 138 | if (translation.y<0) { 139 | NSLog(@"上移"); 140 | // //向上滑动 141 | // self.parentScrollView.scrollEnabled = YES; 142 | // self.chidlScrollView.scrollEnabled = NO; 143 | }else{ 144 | NSLog(@"下移"); 145 | // self.parentScrollView.scrollEnabled = YES; 146 | 147 | //向下滑动 148 | } 149 | // self.chidlScrollView.contentOffset = self.offset; 150 | if (self.moveDirectionDownOrUpBlock) { 151 | self.moveDirectionDownOrUpBlock(translation.y); 152 | } 153 | 154 | }else{ 155 | self.chidlScrollView.scrollEnabled = NO; 156 | self.parentScrollView.scrollEnabled = YES; 157 | 158 | } 159 | 160 | 161 | } 162 | 163 | 164 | @end 165 | -------------------------------------------------------------------------------- /个人主页demo/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // 个人主页demo 4 | // 5 | // Created by hyw on 2018/11/14. 6 | // Copyright © 2018年 bksx. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | --------------------------------------------------------------------------------