├── .gitignore
├── README.md
├── WaterFlowLayout.xcodeproj
├── project.pbxproj
├── project.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcuserdata
│ │ └── mac.xcuserdatad
│ │ └── UserInterfaceState.xcuserstate
└── xcuserdata
│ └── mac.xcuserdatad
│ ├── xcdebugger
│ └── Breakpoints_v2.xcbkptlist
│ └── xcschemes
│ ├── WaterFlowLayout.xcscheme
│ └── xcschememanagement.plist
├── WaterFlowLayout
├── 1.plist
├── 2.plist
├── 3.plist
├── AppDelegate.h
├── AppDelegate.m
├── Assets.xcassets
│ └── AppIcon.appiconset
│ │ └── Contents.json
├── Base.lproj
│ ├── LaunchScreen.storyboard
│ └── Main.storyboard
├── Info.plist
├── SDWebImage
│ ├── NSData+ImageContentType.h
│ ├── NSData+ImageContentType.m
│ ├── SDImageCache.h
│ ├── SDImageCache.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+WebCacheOperation.h
│ └── UIView+WebCacheOperation.m
├── SPEasyLoading
│ ├── SPBlankView
│ │ ├── SPBlankView.h
│ │ └── SPBlankView.m
│ ├── SPCategories
│ │ ├── UICollectionView+SPEasyLoading.h
│ │ ├── UICollectionView+SPEasyLoading.m
│ │ ├── UIScrollView+SPEasyLoading.h
│ │ └── UIScrollView+SPEasyLoading.m
│ ├── SPEasyLoadingForCollectionView.h
│ ├── SPEasyLoadingForTableView.h
│ ├── SPEasyLoadingHeader.h
│ ├── SPHeightCache
│ │ ├── UITableView+SPHeightCache.h
│ │ ├── UITableView+SPHeightCache.m
│ │ ├── UITableView+SPTemplateLayoutCell.h
│ │ └── UITableView+SPTemplateLayoutCell.m
│ ├── SPRefreshView
│ │ ├── SPLoadMoreView.h
│ │ ├── SPLoadMoreView.m
│ │ ├── SPRefreshControl.h
│ │ └── SPRefreshControl.m
│ └── SPSupportFiles
│ │ ├── sp_arrow@2x.png
│ │ └── sp_blank@2x.png
├── SPProductModel
│ ├── SPProductModel.h
│ └── SPProductModel.m
├── SPSelfSizeCell.h
├── SPSelfSizeCell.m
├── SPWaterFlowLayout.h
├── SPWaterFlowLayout.m
├── TestView.xib
├── UICollectionViewCell+FeedData.h
├── UICollectionViewCell+FeedData.m
├── ViewController.h
├── ViewController.m
├── YYFPSLabel
│ ├── YYFPSLabel.h
│ ├── YYFPSLabel.m
│ ├── YYWeakProxy.h
│ └── YYWeakProxy.m
└── main.m
└── waterflow.gif
/.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
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 | # SPWaterFlowLayout
2 |
3 | [简书地址](http://www.jianshu.com/p/bd856b5e140a)
4 |
5 | 
6 |
7 | ## how to use
8 |
9 | **initialize**
10 | ```
11 | SPWaterFlowLayout *flowlayout = [[SPWaterFlowLayout alloc] init];
12 | flowlayout.columnNumber = 2;
13 | flowlayout.interitemSpacing = 10;
14 | flowlayout.lineSpacing = 10;
15 | flowlayout.pageSize = 54;
16 | flowlayout.xibName = @"TestView";
17 | UICollectionView *test = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowlayout];
18 | test.contentInset = UIEdgeInsetsMake(10, 10, 5, 10);
19 | [self.view addSubview:test];
20 | test.delegate = self;
21 | test.dataSource = self;
22 | [test registerNib:[UINib nibWithNibName:@"TestView" bundle:nil] forCellWithReuseIdentifier:@"Cell"];
23 | test.backgroundColor = [UIColor whiteColor];
24 | ```
25 | update**SPWaterFlowLayout**'s property `datas` when Refresh or LoadMore
26 |
27 | **Refresh**
28 | ```
29 | test.refreshDataCallBack = ^{
30 | dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
31 | self.pageTag = 0;
32 | NSArray *datas = [SPProductModel productWithIndex:0];
33 | flowlayout.datas = datas;
34 | wtest.sp_datas = [datas mutableCopy];
35 | [wtest doneLoadDatas];
36 | [wtest reloadData];
37 | });
38 | };
39 | ```
40 | **LoadMore**
41 | ```
42 | test.loadMoreDataCallBack = ^{
43 | self.pageTag ++;
44 | dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
45 | NSArray *datas = [SPProductModel productWithIndex:self.pageTag];
46 | NSArray *total = [flowlayout.datas arrayByAddingObjectsFromArray:datas];
47 | flowlayout.datas = total;
48 | wtest.sp_datas = [total mutableCopy];
49 | [wtest doneLoadDatas];
50 | [wtest reloadData];
51 | });
52 | };
53 | ```
54 |
--------------------------------------------------------------------------------
/WaterFlowLayout.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/WaterFlowLayout.xcodeproj/project.xcworkspace/xcuserdata/mac.xcuserdatad/UserInterfaceState.xcuserstate:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Tr2e/SPWaterFlowLayout/64f1ded92f26ea32297361ff80a2bdcc849f7992/WaterFlowLayout.xcodeproj/project.xcworkspace/xcuserdata/mac.xcuserdatad/UserInterfaceState.xcuserstate
--------------------------------------------------------------------------------
/WaterFlowLayout.xcodeproj/xcuserdata/mac.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
8 |
20 |
21 |
22 |
24 |
36 |
37 |
38 |
40 |
46 |
47 |
48 |
50 |
62 |
63 |
64 |
66 |
78 |
79 |
80 |
82 |
94 |
95 |
96 |
98 |
110 |
111 |
112 |
114 |
126 |
127 |
128 |
130 |
142 |
143 |
144 |
146 |
158 |
159 |
160 |
162 |
174 |
175 |
176 |
178 |
190 |
191 |
205 |
206 |
220 |
221 |
222 |
223 |
224 |
226 |
238 |
239 |
240 |
242 |
254 |
255 |
256 |
257 |
258 |
--------------------------------------------------------------------------------
/WaterFlowLayout.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/WaterFlowLayout.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
32 |
33 |
39 |
40 |
41 |
42 |
43 |
44 |
54 |
56 |
62 |
63 |
64 |
65 |
66 |
67 |
73 |
75 |
81 |
82 |
83 |
84 |
86 |
87 |
90 |
91 |
92 |
--------------------------------------------------------------------------------
/WaterFlowLayout.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/xcschememanagement.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | SchemeUserState
6 |
7 | WaterFlowLayout.xcscheme
8 |
9 | orderHint
10 | 0
11 |
12 |
13 | SuppressBuildableAutocreation
14 |
15 | 0464A0741F5FECFF00513364
16 |
17 | primary
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/WaterFlowLayout/AppDelegate.h:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.h
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/6.
6 | // Copyright © 2017年 Tr2e. 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 |
--------------------------------------------------------------------------------
/WaterFlowLayout/AppDelegate.m:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.m
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/6.
6 | // Copyright © 2017年 Tr2e. 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 |
--------------------------------------------------------------------------------
/WaterFlowLayout/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "29x29",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "29x29",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "40x40",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "40x40",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "60x60",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "60x60",
31 | "scale" : "3x"
32 | },
33 | {
34 | "idiom" : "ipad",
35 | "size" : "29x29",
36 | "scale" : "1x"
37 | },
38 | {
39 | "idiom" : "ipad",
40 | "size" : "29x29",
41 | "scale" : "2x"
42 | },
43 | {
44 | "idiom" : "ipad",
45 | "size" : "40x40",
46 | "scale" : "1x"
47 | },
48 | {
49 | "idiom" : "ipad",
50 | "size" : "40x40",
51 | "scale" : "2x"
52 | },
53 | {
54 | "idiom" : "ipad",
55 | "size" : "76x76",
56 | "scale" : "1x"
57 | },
58 | {
59 | "idiom" : "ipad",
60 | "size" : "76x76",
61 | "scale" : "2x"
62 | }
63 | ],
64 | "info" : {
65 | "version" : 1,
66 | "author" : "xcode"
67 | }
68 | }
--------------------------------------------------------------------------------
/WaterFlowLayout/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 |
27 |
28 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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 |
--------------------------------------------------------------------------------
/WaterFlowLayout/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | NSAppTransportSecurity
6 |
7 | NSAllowsArbitraryLoads
8 |
9 |
10 | CFBundleDevelopmentRegion
11 | en
12 | CFBundleExecutable
13 | $(EXECUTABLE_NAME)
14 | CFBundleIdentifier
15 | $(PRODUCT_BUNDLE_IDENTIFIER)
16 | CFBundleInfoDictionaryVersion
17 | 6.0
18 | CFBundleName
19 | $(PRODUCT_NAME)
20 | CFBundlePackageType
21 | APPL
22 | CFBundleShortVersionString
23 | 1.0
24 | CFBundleVersion
25 | 1
26 | LSRequiresIPhoneOS
27 |
28 | UILaunchStoryboardName
29 | LaunchScreen
30 | UIMainStoryboardFile
31 | Main
32 | UIRequiredDeviceCapabilities
33 |
34 | armv7
35 |
36 | UISupportedInterfaceOrientations
37 |
38 | UIInterfaceOrientationPortrait
39 | UIInterfaceOrientationLandscapeLeft
40 | UIInterfaceOrientationLandscapeRight
41 |
42 | UISupportedInterfaceOrientations~ipad
43 |
44 | UIInterfaceOrientationPortrait
45 | UIInterfaceOrientationPortraitUpsideDown
46 | UIInterfaceOrientationLandscapeLeft
47 | UIInterfaceOrientationLandscapeRight
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SDWebImage/NSData+ImageContentType.h:
--------------------------------------------------------------------------------
1 | //
2 | // Created by Fabrice Aneche on 06/01/14.
3 | // Copyright (c) 2014 Dailymotion. All rights reserved.
4 | //
5 |
6 | #import
7 |
8 | @interface NSData (ImageContentType)
9 |
10 | /**
11 | * Compute the content type for an image data
12 | *
13 | * @param data the input data
14 | *
15 | * @return the content type as string (i.e. image/jpeg, image/gif)
16 | */
17 | + (NSString *)sd_contentTypeForImageData:(NSData *)data;
18 |
19 | @end
20 |
21 |
22 | @interface NSData (ImageContentTypeDeprecated)
23 |
24 | + (NSString *)contentTypeForImageData:(NSData *)data __deprecated_msg("Use `sd_contentTypeForImageData:`");
25 |
26 | @end
27 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SDWebImage/NSData+ImageContentType.m:
--------------------------------------------------------------------------------
1 | //
2 | // Created by Fabrice Aneche on 06/01/14.
3 | // Copyright (c) 2014 Dailymotion. All rights reserved.
4 | //
5 |
6 | #import "NSData+ImageContentType.h"
7 |
8 |
9 | @implementation NSData (ImageContentType)
10 |
11 | + (NSString *)sd_contentTypeForImageData:(NSData *)data {
12 | uint8_t c;
13 | [data getBytes:&c length:1];
14 | switch (c) {
15 | case 0xFF:
16 | return @"image/jpeg";
17 | case 0x89:
18 | return @"image/png";
19 | case 0x47:
20 | return @"image/gif";
21 | case 0x49:
22 | case 0x4D:
23 | return @"image/tiff";
24 | case 0x52:
25 | // R as RIFF for WEBP
26 | if ([data length] < 12) {
27 | return nil;
28 | }
29 |
30 | NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
31 | if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
32 | return @"image/webp";
33 | }
34 |
35 | return nil;
36 | }
37 | return nil;
38 | }
39 |
40 | @end
41 |
42 |
43 | @implementation NSData (ImageContentTypeDeprecated)
44 |
45 | + (NSString *)contentTypeForImageData:(NSData *)data {
46 | return [self sd_contentTypeForImageData:data];
47 | }
48 |
49 | @end
50 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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 | typedef NS_ENUM(NSInteger, SDImageCacheType) {
13 | /**
14 | * The image wasn't available the SDWebImage caches, but was downloaded from the web.
15 | */
16 | SDImageCacheTypeNone,
17 | /**
18 | * The image was obtained from the disk cache.
19 | */
20 | SDImageCacheTypeDisk,
21 | /**
22 | * The image was obtained from the memory cache.
23 | */
24 | SDImageCacheTypeMemory
25 | };
26 |
27 | typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType);
28 |
29 | typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache);
30 |
31 | typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize);
32 |
33 | /**
34 | * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed
35 | * asynchronous so it doesn’t add unnecessary latency to the UI.
36 | */
37 | @interface SDImageCache : NSObject
38 |
39 | /**
40 | * Decompressing images that are downloaded and cached can improve peformance but can consume lot of memory.
41 | * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption.
42 | */
43 | @property (assign, nonatomic) BOOL shouldDecompressImages;
44 |
45 | /**
46 | * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory.
47 | */
48 | @property (assign, nonatomic) NSUInteger maxMemoryCost;
49 |
50 | /**
51 | * The maximum length of time to keep an image in the cache, in seconds
52 | */
53 | @property (assign, nonatomic) NSInteger maxCacheAge;
54 |
55 | /**
56 | * The maximum size of the cache, in bytes.
57 | */
58 | @property (assign, nonatomic) NSUInteger maxCacheSize;
59 |
60 | /**
61 | * Returns global shared cache instance
62 | *
63 | * @return SDImageCache global instance
64 | */
65 | + (SDImageCache *)sharedImageCache;
66 |
67 | /**
68 | * Init a new cache store with a specific namespace
69 | *
70 | * @param ns The namespace to use for this cache store
71 | */
72 | - (id)initWithNamespace:(NSString *)ns;
73 |
74 | /**
75 | * Add a read-only cache path to search for images pre-cached by SDImageCache
76 | * Useful if you want to bundle pre-loaded images with your app
77 | *
78 | * @param path The path to use for this read-only cache path
79 | */
80 | - (void)addReadOnlyCachePath:(NSString *)path;
81 |
82 | /**
83 | * Store an image into memory and disk cache at the given key.
84 | *
85 | * @param image The image to store
86 | * @param key The unique image cache key, usually it's image absolute URL
87 | */
88 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key;
89 |
90 | /**
91 | * Store an image into memory and optionally disk cache at the given key.
92 | *
93 | * @param image The image to store
94 | * @param key The unique image cache key, usually it's image absolute URL
95 | * @param toDisk Store the image to disk cache if YES
96 | */
97 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;
98 |
99 | /**
100 | * Store an image into memory and optionally disk cache at the given key.
101 | *
102 | * @param image The image to store
103 | * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage
104 | * @param imageData The image data as returned by the server, this representation will be used for disk storage
105 | * instead of converting the given image object into a storable/compressed image format in order
106 | * to save quality and CPU
107 | * @param key The unique image cache key, usually it's image absolute URL
108 | * @param toDisk Store the image to disk cache if YES
109 | */
110 | - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk;
111 |
112 | /**
113 | * Query the disk cache asynchronously.
114 | *
115 | * @param key The unique key used to store the wanted image
116 | */
117 | - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;
118 |
119 | /**
120 | * Query the memory cache synchronously.
121 | *
122 | * @param key The unique key used to store the wanted image
123 | */
124 | - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;
125 |
126 | /**
127 | * Query the disk cache synchronously after checking the memory cache.
128 | *
129 | * @param key The unique key used to store the wanted image
130 | */
131 | - (UIImage *)imageFromDiskCacheForKey:(NSString *)key;
132 |
133 | /**
134 | * Remove the image from memory and disk cache synchronously
135 | *
136 | * @param key The unique image cache key
137 | */
138 | - (void)removeImageForKey:(NSString *)key;
139 |
140 |
141 | /**
142 | * Remove the image from memory and disk cache synchronously
143 | *
144 | * @param key The unique image cache key
145 | * @param completion An block that should be executed after the image has been removed (optional)
146 | */
147 | - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion;
148 |
149 | /**
150 | * Remove the image from memory and optionally disk cache synchronously
151 | *
152 | * @param key The unique image cache key
153 | * @param fromDisk Also remove cache entry from disk if YES
154 | */
155 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;
156 |
157 | /**
158 | * Remove the image from memory and optionally disk cache synchronously
159 | *
160 | * @param key The unique image cache key
161 | * @param fromDisk Also remove cache entry from disk if YES
162 | * @param completion An block that should be executed after the image has been removed (optional)
163 | */
164 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion;
165 |
166 | /**
167 | * Clear all memory cached images
168 | */
169 | - (void)clearMemory;
170 |
171 | /**
172 | * Clear all disk cached images. Non-blocking method - returns immediately.
173 | * @param completion An block that should be executed after cache expiration completes (optional)
174 | */
175 | - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion;
176 |
177 | /**
178 | * Clear all disk cached images
179 | * @see clearDiskOnCompletion:
180 | */
181 | - (void)clearDisk;
182 |
183 | /**
184 | * Remove all expired cached image from disk. Non-blocking method - returns immediately.
185 | * @param completionBlock An block that should be executed after cache expiration completes (optional)
186 | */
187 | - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock;
188 |
189 | /**
190 | * Remove all expired cached image from disk
191 | * @see cleanDiskWithCompletionBlock:
192 | */
193 | - (void)cleanDisk;
194 |
195 | /**
196 | * Get the size used by the disk cache
197 | */
198 | - (NSUInteger)getSize;
199 |
200 | /**
201 | * Get the number of images in the disk cache
202 | */
203 | - (NSUInteger)getDiskCount;
204 |
205 | /**
206 | * Asynchronously calculate the disk cache's size.
207 | */
208 | - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock;
209 |
210 | /**
211 | * Async check if image exists in disk cache already (does not load the image)
212 | *
213 | * @param key the key describing the url
214 | * @param completionBlock the block to be executed when the check is done.
215 | * @note the completion block will be always executed on the main queue
216 | */
217 | - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
218 |
219 | /**
220 | * Check if image exists in disk cache already (does not load the image)
221 | *
222 | * @param key the key describing the url
223 | *
224 | * @return YES if an image exists for the given key
225 | */
226 | - (BOOL)diskImageExistsWithKey:(NSString *)key;
227 |
228 | /**
229 | * Get the cache path for a certain key (needs the cache path root folder)
230 | *
231 | * @param key the key (can be obtained from url using cacheKeyForURL)
232 | * @param path the cach path root folder
233 | *
234 | * @return the cache path
235 | */
236 | - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path;
237 |
238 | /**
239 | * Get the default cache path for a certain key
240 | *
241 | * @param key the key (can be obtained from url using cacheKeyForURL)
242 | *
243 | * @return the default cache path
244 | */
245 | - (NSString *)defaultCachePathForKey:(NSString *)key;
246 |
247 | @end
248 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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 | #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0
17 | #error SDWebImage doesn't support Deployement Target version < 5.0
18 | #endif
19 |
20 | #if !TARGET_OS_IPHONE
21 | #import
22 | #ifndef UIImage
23 | #define UIImage NSImage
24 | #endif
25 | #ifndef UIImageView
26 | #define UIImageView NSImageView
27 | #endif
28 | #else
29 |
30 | #import
31 |
32 | #endif
33 |
34 | #ifndef NS_ENUM
35 | #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
36 | #endif
37 |
38 | #ifndef NS_OPTIONS
39 | #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type
40 | #endif
41 |
42 | #if OS_OBJECT_USE_OBJC
43 | #undef SDDispatchQueueRelease
44 | #undef SDDispatchQueueSetterSementics
45 | #define SDDispatchQueueRelease(q)
46 | #define SDDispatchQueueSetterSementics strong
47 | #else
48 | #undef SDDispatchQueueRelease
49 | #undef SDDispatchQueueSetterSementics
50 | #define SDDispatchQueueRelease(q) (dispatch_release(q))
51 | #define SDDispatchQueueSetterSementics assign
52 | #endif
53 |
54 | extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image);
55 |
56 | typedef void(^SDWebImageNoParamsBlock)();
57 |
58 | #define dispatch_main_sync_safe(block)\
59 | if ([NSThread isMainThread]) {\
60 | block();\
61 | } else {\
62 | dispatch_sync(dispatch_get_main_queue(), block);\
63 | }
64 |
65 | #define dispatch_main_async_safe(block)\
66 | if ([NSThread isMainThread]) {\
67 | block();\
68 | } else {\
69 | dispatch_async(dispatch_get_main_queue(), block);\
70 | }
71 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SDWebImage/SDWebImageCompat.m:
--------------------------------------------------------------------------------
1 | //
2 | // SDWebImageCompat.m
3 | // SDWebImage
4 | //
5 | // Created by Olivier Poitrey on 11/12/12.
6 | // Copyright (c) 2012 Dailymotion. All rights reserved.
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 *key, UIImage *image) {
16 | if (!image) {
17 | return nil;
18 | }
19 |
20 | if ([image.images count] > 0) {
21 | NSMutableArray *scaledImages = [NSMutableArray array];
22 |
23 | for (UIImage *tempImage in image.images) {
24 | [scaledImages addObject:SDScaledImageForKey(key, tempImage)];
25 | }
26 |
27 | return [UIImage animatedImageWithImages:scaledImages duration:image.duration];
28 | }
29 | else {
30 | if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
31 | CGFloat scale = 1.0;
32 | if (key.length >= 8) {
33 | // Search @2x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x. + 4 len ext)
34 | NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)];
35 | if (range.location != NSNotFound) {
36 | scale = 2.0;
37 | }
38 | }
39 |
40 | UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
41 | image = scaledImage;
42 | }
43 | return image;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SDWebImage/SDWebImageDecoder.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * Created by james on 9/28/11.
6 | *
7 | * For the full copyright and license information, please view the LICENSE
8 | * file that was distributed with this source code.
9 | */
10 |
11 | #import
12 | #import "SDWebImageCompat.h"
13 |
14 | @interface UIImage (ForceDecode)
15 |
16 | + (UIImage *)decodedImageWithImage:(UIImage *)image;
17 |
18 | @end
19 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SDWebImage/SDWebImageDecoder.m:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * Created by james on 9/28/11.
6 | *
7 | * For the full copyright and license information, please view the LICENSE
8 | * file that was distributed with this source code.
9 | */
10 |
11 | #import "SDWebImageDecoder.h"
12 |
13 | @implementation UIImage (ForceDecode)
14 |
15 | + (UIImage *)decodedImageWithImage:(UIImage *)image {
16 | if (image.images) {
17 | // Do not decode animated images
18 | return image;
19 | }
20 |
21 | CGImageRef imageRef = image.CGImage;
22 | CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
23 | CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize};
24 |
25 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
26 | CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
27 |
28 | int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask);
29 | BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone ||
30 | infoMask == kCGImageAlphaNoneSkipFirst ||
31 | infoMask == kCGImageAlphaNoneSkipLast);
32 |
33 | // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB.
34 | // https://developer.apple.com/library/mac/#qa/qa1037/_index.html
35 | if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) {
36 | // Unset the old alpha info.
37 | bitmapInfo &= ~kCGBitmapAlphaInfoMask;
38 |
39 | // Set noneSkipFirst.
40 | bitmapInfo |= kCGImageAlphaNoneSkipFirst;
41 | }
42 | // Some PNGs tell us they have alpha but only 3 components. Odd.
43 | else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) {
44 | // Unset the old alpha info.
45 | bitmapInfo &= ~kCGBitmapAlphaInfoMask;
46 | bitmapInfo |= kCGImageAlphaPremultipliedFirst;
47 | }
48 |
49 | // It calculates the bytes-per-row based on the bitsPerComponent and width arguments.
50 | CGContextRef context = CGBitmapContextCreate(NULL,
51 | imageSize.width,
52 | imageSize.height,
53 | CGImageGetBitsPerComponent(imageRef),
54 | 0,
55 | colorSpace,
56 | bitmapInfo);
57 | CGColorSpaceRelease(colorSpace);
58 |
59 | // If failed, return undecompressed image
60 | if (!context) return image;
61 |
62 | CGContextDrawImage(context, imageRect, imageRef);
63 | CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context);
64 |
65 | CGContextRelease(context);
66 |
67 | UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation];
68 | CGImageRelease(decompressedImageRef);
69 | return decompressedImage;
70 | }
71 |
72 | @end
73 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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 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 ceriticates.
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 | typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) {
55 | /**
56 | * Default value. All download operations will execute in queue style (first-in-first-out).
57 | */
58 | SDWebImageDownloaderFIFOExecutionOrder,
59 |
60 | /**
61 | * All download operations will execute in stack style (last-in-first-out).
62 | */
63 | SDWebImageDownloaderLIFOExecutionOrder
64 | };
65 |
66 | extern NSString *const SDWebImageDownloadStartNotification;
67 | extern NSString *const SDWebImageDownloadStopNotification;
68 |
69 | typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize);
70 |
71 | typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished);
72 |
73 | typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers);
74 |
75 | /**
76 | * Asynchronous downloader dedicated and optimized for image loading.
77 | */
78 | @interface SDWebImageDownloader : NSObject
79 |
80 | /**
81 | * Decompressing images that are downloaded and cached can improve peformance but can consume lot of memory.
82 | * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption.
83 | */
84 | @property (assign, nonatomic) BOOL shouldDecompressImages;
85 |
86 | @property (assign, nonatomic) NSInteger maxConcurrentDownloads;
87 |
88 | /**
89 | * Shows the current amount of downloads that still need to be downloaded
90 | */
91 | @property (readonly, nonatomic) NSUInteger currentDownloadCount;
92 |
93 |
94 | /**
95 | * The timeout value (in seconds) for the download operation. Default: 15.0.
96 | */
97 | @property (assign, nonatomic) NSTimeInterval downloadTimeout;
98 |
99 |
100 | /**
101 | * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`.
102 | */
103 | @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder;
104 |
105 | /**
106 | * Singleton method, returns the shared instance
107 | *
108 | * @return global shared instance of downloader class
109 | */
110 | + (SDWebImageDownloader *)sharedDownloader;
111 |
112 | /**
113 | * Set username
114 | */
115 | @property (strong, nonatomic) NSString *username;
116 |
117 | /**
118 | * Set password
119 | */
120 | @property (strong, nonatomic) NSString *password;
121 |
122 | /**
123 | * Set filter to pick headers for downloading image HTTP request.
124 | *
125 | * This block will be invoked for each downloading image request, returned
126 | * NSDictionary will be used as headers in corresponding HTTP request.
127 | */
128 | @property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter;
129 |
130 | /**
131 | * Set a value for a HTTP header to be appended to each download HTTP request.
132 | *
133 | * @param value The value for the header field. Use `nil` value to remove the header.
134 | * @param field The name of the header field to set.
135 | */
136 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
137 |
138 | /**
139 | * Returns the value of the specified HTTP header field.
140 | *
141 | * @return The value associated with the header field field, or `nil` if there is no corresponding header field.
142 | */
143 | - (NSString *)valueForHTTPHeaderField:(NSString *)field;
144 |
145 | /**
146 | * Sets a subclass of `SDWebImageDownloaderOperation` as the default
147 | * `NSOperation` to be used each time SDWebImage constructs a request
148 | * operation to download an image.
149 | *
150 | * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set
151 | * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`.
152 | */
153 | - (void)setOperationClass:(Class)operationClass;
154 |
155 | /**
156 | * Creates a SDWebImageDownloader async downloader instance with a given URL
157 | *
158 | * The delegate will be informed when the image is finish downloaded or an error has happen.
159 | *
160 | * @see SDWebImageDownloaderDelegate
161 | *
162 | * @param url The URL to the image to download
163 | * @param options The options to be used for this download
164 | * @param progressBlock A block called repeatedly while the image is downloading
165 | * @param completedBlock A block called once the download is completed.
166 | * If the download succeeded, the image parameter is set, in case of error,
167 | * error parameter is set with the error. The last parameter is always YES
168 | * if SDWebImageDownloaderProgressiveDownload isn't use. With the
169 | * SDWebImageDownloaderProgressiveDownload option, this block is called
170 | * repeatedly with the partial image object and the finished argument set to NO
171 | * before to be called a last time with the full image and finished argument
172 | * set to YES. In case of error, the finished argument is always YES.
173 | *
174 | * @return A cancellable SDWebImageOperation
175 | */
176 | - (id )downloadImageWithURL:(NSURL *)url
177 | options:(SDWebImageDownloaderOptions)options
178 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
179 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock;
180 |
181 | /**
182 | * Sets the download queue suspension state
183 | */
184 | - (void)setSuspended:(BOOL)suspended;
185 |
186 | @end
187 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SDWebImage/SDWebImageDownloader.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 "SDWebImageDownloader.h"
10 | #import "SDWebImageDownloaderOperation.h"
11 | #import
12 |
13 | NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification";
14 | NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification";
15 |
16 | static NSString *const kProgressCallbackKey = @"progress";
17 | static NSString *const kCompletedCallbackKey = @"completed";
18 |
19 | @interface SDWebImageDownloader ()
20 |
21 | @property (strong, nonatomic) NSOperationQueue *downloadQueue;
22 | @property (weak, nonatomic) NSOperation *lastAddedOperation;
23 | @property (assign, nonatomic) Class operationClass;
24 | @property (strong, nonatomic) NSMutableDictionary *URLCallbacks;
25 | @property (strong, nonatomic) NSMutableDictionary *HTTPHeaders;
26 | // This queue is used to serialize the handling of the network responses of all the download operation in a single queue
27 | @property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue;
28 |
29 | @end
30 |
31 | @implementation SDWebImageDownloader
32 |
33 | + (void)initialize {
34 | // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator )
35 | // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import
36 | if (NSClassFromString(@"SDNetworkActivityIndicator")) {
37 |
38 | #pragma clang diagnostic push
39 | #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
40 | id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")];
41 | #pragma clang diagnostic pop
42 |
43 | // Remove observer in case it was previously added.
44 | [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil];
45 | [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil];
46 |
47 | [[NSNotificationCenter defaultCenter] addObserver:activityIndicator
48 | selector:NSSelectorFromString(@"startActivity")
49 | name:SDWebImageDownloadStartNotification object:nil];
50 | [[NSNotificationCenter defaultCenter] addObserver:activityIndicator
51 | selector:NSSelectorFromString(@"stopActivity")
52 | name:SDWebImageDownloadStopNotification object:nil];
53 | }
54 | }
55 |
56 | + (SDWebImageDownloader *)sharedDownloader {
57 | static dispatch_once_t once;
58 | static id instance;
59 | dispatch_once(&once, ^{
60 | instance = [self new];
61 | });
62 | return instance;
63 | }
64 |
65 | - (id)init {
66 | if ((self = [super init])) {
67 | _operationClass = [SDWebImageDownloaderOperation class];
68 | _shouldDecompressImages = YES;
69 | _executionOrder = SDWebImageDownloaderFIFOExecutionOrder;
70 | _downloadQueue = [NSOperationQueue new];
71 | _downloadQueue.maxConcurrentOperationCount = 6;
72 | _URLCallbacks = [NSMutableDictionary new];
73 | _HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"];
74 | _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
75 | _downloadTimeout = 15.0;
76 | }
77 | return self;
78 | }
79 |
80 | - (void)dealloc {
81 | [self.downloadQueue cancelAllOperations];
82 | SDDispatchQueueRelease(_barrierQueue);
83 | }
84 |
85 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field {
86 | if (value) {
87 | self.HTTPHeaders[field] = value;
88 | }
89 | else {
90 | [self.HTTPHeaders removeObjectForKey:field];
91 | }
92 | }
93 |
94 | - (NSString *)valueForHTTPHeaderField:(NSString *)field {
95 | return self.HTTPHeaders[field];
96 | }
97 |
98 | - (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads {
99 | _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads;
100 | }
101 |
102 | - (NSUInteger)currentDownloadCount {
103 | return _downloadQueue.operationCount;
104 | }
105 |
106 | - (NSInteger)maxConcurrentDownloads {
107 | return _downloadQueue.maxConcurrentOperationCount;
108 | }
109 |
110 | - (void)setOperationClass:(Class)operationClass {
111 | _operationClass = operationClass ?: [SDWebImageDownloaderOperation class];
112 | }
113 |
114 | - (id )downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock {
115 | __block SDWebImageDownloaderOperation *operation;
116 | __weak SDWebImageDownloader *wself = self;
117 |
118 | [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{
119 | NSTimeInterval timeoutInterval = wself.downloadTimeout;
120 | if (timeoutInterval == 0.0) {
121 | timeoutInterval = 15.0;
122 | }
123 |
124 | // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise
125 | NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval];
126 | request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies);
127 | request.HTTPShouldUsePipelining = YES;
128 | if (wself.headersFilter) {
129 | request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]);
130 | }
131 | else {
132 | request.allHTTPHeaderFields = wself.HTTPHeaders;
133 | }
134 | operation = [[wself.operationClass alloc] initWithRequest:request
135 | options:options
136 | progress:^(NSInteger receivedSize, NSInteger expectedSize) {
137 | SDWebImageDownloader *sself = wself;
138 | if (!sself) return;
139 | __block NSArray *callbacksForURL;
140 | dispatch_sync(sself.barrierQueue, ^{
141 | callbacksForURL = [sself.URLCallbacks[url] copy];
142 | });
143 | for (NSDictionary *callbacks in callbacksForURL) {
144 | SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey];
145 | if (callback) callback(receivedSize, expectedSize);
146 | }
147 | }
148 | completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
149 | SDWebImageDownloader *sself = wself;
150 | if (!sself) return;
151 | __block NSArray *callbacksForURL;
152 | dispatch_barrier_sync(sself.barrierQueue, ^{
153 | callbacksForURL = [sself.URLCallbacks[url] copy];
154 | if (finished) {
155 | [sself.URLCallbacks removeObjectForKey:url];
156 | }
157 | });
158 | for (NSDictionary *callbacks in callbacksForURL) {
159 | SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey];
160 | if (callback) callback(image, data, error, finished);
161 | }
162 | }
163 | cancelled:^{
164 | SDWebImageDownloader *sself = wself;
165 | if (!sself) return;
166 | dispatch_barrier_async(sself.barrierQueue, ^{
167 | [sself.URLCallbacks removeObjectForKey:url];
168 | });
169 | }];
170 | operation.shouldDecompressImages = wself.shouldDecompressImages;
171 |
172 | if (wself.username && wself.password) {
173 | operation.credential = [NSURLCredential credentialWithUser:wself.username password:wself.password persistence:NSURLCredentialPersistenceForSession];
174 | }
175 |
176 | if (options & SDWebImageDownloaderHighPriority) {
177 | operation.queuePriority = NSOperationQueuePriorityHigh;
178 | } else if (options & SDWebImageDownloaderLowPriority) {
179 | operation.queuePriority = NSOperationQueuePriorityLow;
180 | }
181 |
182 | [wself.downloadQueue addOperation:operation];
183 | if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
184 | // Emulate LIFO execution order by systematically adding new operations as last operation's dependency
185 | [wself.lastAddedOperation addDependency:operation];
186 | wself.lastAddedOperation = operation;
187 | }
188 | }];
189 |
190 | return operation;
191 | }
192 |
193 | - (void)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock andCompletedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(NSURL *)url createCallback:(SDWebImageNoParamsBlock)createCallback {
194 | // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data.
195 | if (url == nil) {
196 | if (completedBlock != nil) {
197 | completedBlock(nil, nil, nil, NO);
198 | }
199 | return;
200 | }
201 |
202 | dispatch_barrier_sync(self.barrierQueue, ^{
203 | BOOL first = NO;
204 | if (!self.URLCallbacks[url]) {
205 | self.URLCallbacks[url] = [NSMutableArray new];
206 | first = YES;
207 | }
208 |
209 | // Handle single download of simultaneous download request for the same URL
210 | NSMutableArray *callbacksForURL = self.URLCallbacks[url];
211 | NSMutableDictionary *callbacks = [NSMutableDictionary new];
212 | if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy];
213 | if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy];
214 | [callbacksForURL addObject:callbacks];
215 | self.URLCallbacks[url] = callbacksForURL;
216 |
217 | if (first) {
218 | createCallback();
219 | }
220 | });
221 | }
222 |
223 | - (void)setSuspended:(BOOL)suspended {
224 | [self.downloadQueue setSuspended:suspended];
225 | }
226 |
227 | @end
228 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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 | @interface SDWebImageDownloaderOperation : NSOperation
14 |
15 | /**
16 | * The request used by the operation's connection.
17 | */
18 | @property (strong, nonatomic, readonly) NSURLRequest *request;
19 |
20 |
21 | @property (assign, nonatomic) BOOL shouldDecompressImages;
22 |
23 | /**
24 | * Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
25 | *
26 | * This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
27 | */
28 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage;
29 |
30 | /**
31 | * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
32 | *
33 | * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
34 | */
35 | @property (nonatomic, strong) NSURLCredential *credential;
36 |
37 | /**
38 | * The SDWebImageDownloaderOptions for the receiver.
39 | */
40 | @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options;
41 |
42 | /**
43 | * Initializes a `SDWebImageDownloaderOperation` object
44 | *
45 | * @see SDWebImageDownloaderOperation
46 | *
47 | * @param request the URL request
48 | * @param options downloader options
49 | * @param progressBlock the block executed when a new chunk of data arrives.
50 | * @note the progress block is executed on a background queue
51 | * @param completedBlock the block executed when the download is done.
52 | * @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
53 | * @param cancelBlock the block executed if the download (operation) is cancelled
54 | *
55 | * @return the initialized instance
56 | */
57 | - (id)initWithRequest:(NSURLRequest *)request
58 | options:(SDWebImageDownloaderOptions)options
59 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
60 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock
61 | cancelled:(SDWebImageNoParamsBlock)cancelBlock;
62 |
63 | @end
64 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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 embeded 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 ceriticates.
62 | * Useful for testing purposes. Use with caution in production.
63 | */
64 | SDWebImageAllowInvalidSSLCertificates = 1 << 7,
65 |
66 | /**
67 | * By default, image are loaded in the order they were queued. This flag move them to
68 | * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which
69 | * could take a while).
70 | */
71 | SDWebImageHighPriority = 1 << 8,
72 |
73 | /**
74 | * By default, placeholder images are loaded while the image is loading. This flag will delay the loading
75 | * of the placeholder image until after the image has finished loading.
76 | */
77 | SDWebImageDelayPlaceholder = 1 << 9,
78 |
79 | /**
80 | * We usually don't call transformDownloadedImage delegate method on animated images,
81 | * as most transformation code would mangle it.
82 | * Use this flag to transform them anyway.
83 | */
84 | SDWebImageTransformAnimatedImage = 1 << 10,
85 | };
86 |
87 | typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL);
88 |
89 | typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL);
90 |
91 | typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url);
92 |
93 |
94 | @class SDWebImageManager;
95 |
96 | @protocol SDWebImageManagerDelegate
97 |
98 | @optional
99 |
100 | /**
101 | * Controls which image should be downloaded when the image is not found in the cache.
102 | *
103 | * @param imageManager The current `SDWebImageManager`
104 | * @param imageURL The url of the image to be downloaded
105 | *
106 | * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied.
107 | */
108 | - (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL;
109 |
110 | /**
111 | * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory.
112 | * NOTE: This method is called from a global queue in order to not to block the main thread.
113 | *
114 | * @param imageManager The current `SDWebImageManager`
115 | * @param image The image to transform
116 | * @param imageURL The url of the image to transform
117 | *
118 | * @return The transformed image object.
119 | */
120 | - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL;
121 |
122 | @end
123 |
124 | /**
125 | * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes.
126 | * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache).
127 | * You can use this class directly to benefit from web image downloading with caching in another context than
128 | * a UIView.
129 | *
130 | * Here is a simple example of how to use SDWebImageManager:
131 | *
132 | * @code
133 |
134 | SDWebImageManager *manager = [SDWebImageManager sharedManager];
135 | [manager downloadWithURL:imageURL
136 | options:0
137 | progress:nil
138 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
139 | if (image) {
140 | // do something with image
141 | }
142 | }];
143 |
144 | * @endcode
145 | */
146 | @interface SDWebImageManager : NSObject
147 |
148 | @property (weak, nonatomic) id delegate;
149 |
150 | @property (strong, nonatomic, readonly) SDImageCache *imageCache;
151 | @property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader;
152 |
153 | /**
154 | * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can
155 | * be used to remove dynamic part of an image URL.
156 | *
157 | * The following example sets a filter in the application delegate that will remove any query-string from the
158 | * URL before to use it as a cache key:
159 | *
160 | * @code
161 |
162 | [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) {
163 | url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
164 | return [url absoluteString];
165 | }];
166 |
167 | * @endcode
168 | */
169 | @property (nonatomic, copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter;
170 |
171 | /**
172 | * Returns global SDWebImageManager instance.
173 | *
174 | * @return SDWebImageManager shared instance
175 | */
176 | + (SDWebImageManager *)sharedManager;
177 |
178 | /**
179 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise.
180 | *
181 | * @param url The URL to the image
182 | * @param options A mask to specify options to use for this request
183 | * @param progressBlock A block called while image is downloading
184 | * @param completedBlock A block called when operation has been completed.
185 | *
186 | * This parameter is required.
187 | *
188 | * This block has no return value and takes the requested UIImage as first parameter.
189 | * In case of error the image parameter is nil and the second parameter may contain an NSError.
190 | *
191 | * The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache
192 | * or from the memory cache or from the network.
193 | *
194 | * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is
195 | * downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the
196 | * block is called a last time with the full image and the last parameter set to YES.
197 | *
198 | * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation
199 | */
200 | - (id )downloadImageWithURL:(NSURL *)url
201 | options:(SDWebImageOptions)options
202 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
203 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock;
204 |
205 | /**
206 | * Saves image to cache for given URL
207 | *
208 | * @param image The image to cache
209 | * @param url The URL to the image
210 | *
211 | */
212 |
213 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url;
214 |
215 | /**
216 | * Cancel all current opreations
217 | */
218 | - (void)cancelAll;
219 |
220 | /**
221 | * Check one or more operations running
222 | */
223 | - (BOOL)isRunning;
224 |
225 | /**
226 | * Check if image has already been cached
227 | *
228 | * @param url image url
229 | *
230 | * @return if the image was already cached
231 | */
232 | - (BOOL)cachedImageExistsForURL:(NSURL *)url;
233 |
234 | /**
235 | * Check if image has already been cached on disk only
236 | *
237 | * @param url image url
238 | *
239 | * @return if the image was already cached (disk only)
240 | */
241 | - (BOOL)diskImageExistsForURL:(NSURL *)url;
242 |
243 | /**
244 | * Async check if image has already been cached
245 | *
246 | * @param url image url
247 | * @param completionBlock the block to be executed when the check is finished
248 | *
249 | * @note the completion block is always executed on the main queue
250 | */
251 | - (void)cachedImageExistsForURL:(NSURL *)url
252 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
253 |
254 | /**
255 | * Async check if image has already been cached on disk only
256 | *
257 | * @param url image url
258 | * @param completionBlock the block to be executed when the check is finished
259 | *
260 | * @note the completion block is always executed on the main queue
261 | */
262 | - (void)diskImageExistsForURL:(NSURL *)url
263 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
264 |
265 |
266 | /**
267 | *Return the cache key for a given URL
268 | */
269 | - (NSString *)cacheKeyForURL:(NSURL *)url;
270 |
271 | @end
272 |
273 |
274 | #pragma mark - Deprecated
275 |
276 | typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionBlock`");
277 | typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionWithFinishedBlock`");
278 |
279 |
280 | @interface SDWebImageManager (Deprecated)
281 |
282 | /**
283 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise.
284 | *
285 | * @deprecated This method has been deprecated. Use `downloadImageWithURL:options:progress:completed:`
286 | */
287 | - (id )downloadWithURL:(NSURL *)url
288 | options:(SDWebImageOptions)options
289 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
290 | completed:(SDWebImageCompletedWithFinishedBlock)completedBlock __deprecated_msg("Method deprecated. Use `downloadImageWithURL:options:progress:completed:`");
291 |
292 | @end
293 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(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:(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) 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) dispatch_queue_t prefetcherQueue;
65 |
66 | @property (weak, nonatomic) id delegate;
67 |
68 | /**
69 | * Return the global image prefetcher instance.
70 | */
71 | + (SDWebImagePrefetcher *)sharedImagePrefetcher;
72 |
73 | /**
74 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching,
75 | * currently one image is downloaded at a time,
76 | * and skips images for failed downloads and proceed to the next image in the list
77 | *
78 | * @param urls list of URLs to prefetch
79 | */
80 | - (void)prefetchURLs:(NSArray *)urls;
81 |
82 | /**
83 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching,
84 | * currently one image is downloaded at a time,
85 | * and skips images for failed downloads and proceed to the next image in the list
86 | *
87 | * @param urls list of URLs to prefetch
88 | * @param progressBlock block to be called when progress updates;
89 | * first parameter is the number of completed (successful or not) requests,
90 | * second parameter is the total number of images originally requested to be prefetched
91 | * @param completionBlock block to be called when prefetching is completed
92 | * first param is the number of completed (successful or not) requests,
93 | * second parameter is the number of skipped requests
94 | */
95 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock;
96 |
97 | /**
98 | * Remove and cancel queued list
99 | */
100 | - (void)cancelPrefetching;
101 |
102 |
103 | @end
104 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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 | #if (!defined(DEBUG) && !defined (SD_VERBOSE)) || defined(SD_LOG_NONE)
12 | #define NSLog(...)
13 | #endif
14 |
15 | @interface SDWebImagePrefetcher ()
16 |
17 | @property (strong, nonatomic) SDWebImageManager *manager;
18 | @property (strong, nonatomic) NSArray *prefetchURLs;
19 | @property (assign, nonatomic) NSUInteger requestedCount;
20 | @property (assign, nonatomic) NSUInteger skippedCount;
21 | @property (assign, nonatomic) NSUInteger finishedCount;
22 | @property (assign, nonatomic) NSTimeInterval startedTime;
23 | @property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock;
24 | @property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock;
25 |
26 | @end
27 |
28 | @implementation SDWebImagePrefetcher
29 |
30 | + (SDWebImagePrefetcher *)sharedImagePrefetcher {
31 | static dispatch_once_t once;
32 | static id instance;
33 | dispatch_once(&once, ^{
34 | instance = [self new];
35 | });
36 | return instance;
37 | }
38 |
39 | - (id)init {
40 | if ((self = [super init])) {
41 | _manager = [SDWebImageManager new];
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 downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, 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 | NSLog(@"Prefetched %@ out of %@", @(self.finishedCount), @(self.prefetchURLs.count));
69 | }
70 | else {
71 | if (self.progressBlock) {
72 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]);
73 | }
74 | NSLog(@"Prefetched %@ out of %@ (Failed)", @(self.finishedCount), @(self.prefetchURLs.count));
75 |
76 | // Add last failed
77 | self.skippedCount++;
78 | }
79 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) {
80 | [self.delegate imagePrefetcher:self
81 | didPrefetchURL:self.prefetchURLs[index]
82 | finishedCount:self.finishedCount
83 | totalCount:self.prefetchURLs.count
84 | ];
85 | }
86 | if (self.prefetchURLs.count > self.requestedCount) {
87 | dispatch_async(self.prefetcherQueue, ^{
88 | [self startPrefetchingAtIndex:self.requestedCount];
89 | });
90 | }
91 | else if (self.finishedCount == self.requestedCount) {
92 | [self reportStatus];
93 | if (self.completionBlock) {
94 | self.completionBlock(self.finishedCount, self.skippedCount);
95 | self.completionBlock = nil;
96 | }
97 | }
98 | }];
99 | }
100 |
101 | - (void)reportStatus {
102 | NSUInteger total = [self.prefetchURLs count];
103 | NSLog(@"Finished prefetching (%@ successful, %@ skipped, timeElasped %.2f)", @(total - self.skippedCount), @(self.skippedCount), CFAbsoluteTimeGetCurrent() - self.startedTime);
104 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) {
105 | [self.delegate imagePrefetcher:self
106 | didFinishWithTotalCount:(total - self.skippedCount)
107 | skippedCount:self.skippedCount
108 | ];
109 | }
110 | }
111 |
112 | - (void)prefetchURLs:(NSArray *)urls {
113 | [self prefetchURLs:urls progress:nil completed:nil];
114 | }
115 |
116 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock {
117 | [self cancelPrefetching]; // Prevent duplicate prefetch request
118 | self.startedTime = CFAbsoluteTimeGetCurrent();
119 | self.prefetchURLs = urls;
120 | self.completionBlock = completionBlock;
121 | self.progressBlock = progressBlock;
122 |
123 | if(urls.count == 0){
124 | if(completionBlock){
125 | completionBlock(0,0);
126 | }
127 | }else{
128 | // Starts prefetching from the very first image on the list with the max allowed concurrency
129 | NSUInteger listCount = self.prefetchURLs.count;
130 | for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) {
131 | [self startPrefetchingAtIndex:i];
132 | }
133 | }
134 | }
135 |
136 | - (void)cancelPrefetching {
137 | self.prefetchURLs = nil;
138 | self.skippedCount = 0;
139 | self.requestedCount = 0;
140 | self.finishedCount = 0;
141 | [self.manager cancelAll];
142 | }
143 |
144 | @end
145 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SDWebImage/UIImage+GIF.h:
--------------------------------------------------------------------------------
1 | //
2 | // UIImage+GIF.h
3 | // LBGIFImage
4 | //
5 | // Created by Laurin Brandner on 06.01.12.
6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface UIImage (GIF)
12 |
13 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name;
14 |
15 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data;
16 |
17 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size;
18 |
19 | @end
20 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SDWebImage/UIImage+GIF.m:
--------------------------------------------------------------------------------
1 | //
2 | // UIImage+GIF.m
3 | // LBGIFImage
4 | //
5 | // Created by Laurin Brandner on 06.01.12.
6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
7 | //
8 |
9 | #import "UIImage+GIF.h"
10 | #import
11 |
12 | @implementation UIImage (GIF)
13 |
14 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data {
15 | if (!data) {
16 | return nil;
17 | }
18 |
19 | CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
20 |
21 | size_t count = CGImageSourceGetCount(source);
22 |
23 | UIImage *animatedImage;
24 |
25 | if (count <= 1) {
26 | animatedImage = [[UIImage alloc] initWithData:data];
27 | }
28 | else {
29 | NSMutableArray *images = [NSMutableArray array];
30 |
31 | NSTimeInterval duration = 0.0f;
32 |
33 | for (size_t i = 0; i < count; i++) {
34 | CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
35 |
36 | duration += [self sd_frameDurationAtIndex:i source:source];
37 |
38 | [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
39 |
40 | CGImageRelease(image);
41 | }
42 |
43 | if (!duration) {
44 | duration = (1.0f / 10.0f) * count;
45 | }
46 |
47 | animatedImage = [UIImage animatedImageWithImages:images duration:duration];
48 | }
49 |
50 | CFRelease(source);
51 |
52 | return animatedImage;
53 | }
54 |
55 | + (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
56 | float frameDuration = 0.1f;
57 | CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
58 | NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
59 | NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
60 |
61 | NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
62 | if (delayTimeUnclampedProp) {
63 | frameDuration = [delayTimeUnclampedProp floatValue];
64 | }
65 | else {
66 |
67 | NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
68 | if (delayTimeProp) {
69 | frameDuration = [delayTimeProp floatValue];
70 | }
71 | }
72 |
73 | // Many annoying ads specify a 0 duration to make an image flash as quickly as possible.
74 | // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
75 | // a duration of <= 10 ms. See and
76 | // for more information.
77 |
78 | if (frameDuration < 0.011f) {
79 | frameDuration = 0.100f;
80 | }
81 |
82 | CFRelease(cfFrameProperties);
83 | return frameDuration;
84 | }
85 |
86 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name {
87 | CGFloat scale = [UIScreen mainScreen].scale;
88 |
89 | if (scale > 1.0f) {
90 | NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"];
91 |
92 | NSData *data = [NSData dataWithContentsOfFile:retinaPath];
93 |
94 | if (data) {
95 | return [UIImage sd_animatedGIFWithData:data];
96 | }
97 |
98 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
99 |
100 | data = [NSData dataWithContentsOfFile:path];
101 |
102 | if (data) {
103 | return [UIImage sd_animatedGIFWithData:data];
104 | }
105 |
106 | return [UIImage imageNamed:name];
107 | }
108 | else {
109 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
110 |
111 | NSData *data = [NSData dataWithContentsOfFile:path];
112 |
113 | if (data) {
114 | return [UIImage sd_animatedGIFWithData:data];
115 | }
116 |
117 | return [UIImage imageNamed:name];
118 | }
119 | }
120 |
121 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size {
122 | if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) {
123 | return self;
124 | }
125 |
126 | CGSize scaledSize = size;
127 | CGPoint thumbnailPoint = CGPointZero;
128 |
129 | CGFloat widthFactor = size.width / self.size.width;
130 | CGFloat heightFactor = size.height / self.size.height;
131 | CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor;
132 | scaledSize.width = self.size.width * scaleFactor;
133 | scaledSize.height = self.size.height * scaleFactor;
134 |
135 | if (widthFactor > heightFactor) {
136 | thumbnailPoint.y = (size.height - scaledSize.height) * 0.5;
137 | }
138 | else if (widthFactor < heightFactor) {
139 | thumbnailPoint.x = (size.width - scaledSize.width) * 0.5;
140 | }
141 |
142 | NSMutableArray *scaledImages = [NSMutableArray array];
143 |
144 | UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
145 |
146 | for (UIImage *image in self.images) {
147 | [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)];
148 | UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
149 |
150 | [scaledImages addObject:newImage];
151 | }
152 |
153 | UIGraphicsEndImageContext();
154 |
155 | return [UIImage animatedImageWithImages:scaledImages duration:self.duration];
156 | }
157 |
158 | @end
159 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SDWebImage/UIImage+MultiFormat.h:
--------------------------------------------------------------------------------
1 | //
2 | // UIImage+MultiFormat.h
3 | // SDWebImage
4 | //
5 | // Created by Olivier Poitrey on 07/06/13.
6 | // Copyright (c) 2013 Dailymotion. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface UIImage (MultiFormat)
12 |
13 | + (UIImage *)sd_imageWithData:(NSData *)data;
14 |
15 | @end
16 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SDWebImage/UIImage+MultiFormat.m:
--------------------------------------------------------------------------------
1 | //
2 | // UIImage+MultiFormat.m
3 | // SDWebImage
4 | //
5 | // Created by Olivier Poitrey on 07/06/13.
6 | // Copyright (c) 2013 Dailymotion. All rights reserved.
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 | + (UIImage *)sd_imageWithData:(NSData *)data {
21 | UIImage *image;
22 | NSString *imageContentType = [NSData sd_contentTypeForImageData:data];
23 | if ([imageContentType isEqualToString:@"image/gif"]) {
24 | image = [UIImage sd_animatedGIFWithData:data];
25 | }
26 | #ifdef SD_WEBP
27 | else if ([imageContentType isEqualToString:@"image/webp"])
28 | {
29 | image = [UIImage sd_imageWithWebPData:data];
30 | }
31 | #endif
32 | else {
33 | image = [[UIImage alloc] initWithData:data];
34 | UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data];
35 | if (orientation != UIImageOrientationUp) {
36 | image = [UIImage imageWithCGImage:image.CGImage
37 | scale:image.scale
38 | orientation:orientation];
39 | }
40 | }
41 |
42 |
43 | return image;
44 | }
45 |
46 |
47 | +(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData {
48 | UIImageOrientation result = UIImageOrientationUp;
49 | CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL);
50 | if (imageSource) {
51 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
52 | if (properties) {
53 | CFTypeRef val;
54 | int exifOrientation;
55 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation);
56 | if (val) {
57 | CFNumberGetValue(val, kCFNumberIntType, &exifOrientation);
58 | result = [self sd_exifOrientationToiOSOrientation:exifOrientation];
59 | } // else - if it's not set it remains at up
60 | CFRelease((CFTypeRef) properties);
61 | } else {
62 | //NSLog(@"NO PROPERTIES, FAIL");
63 | }
64 | CFRelease(imageSource);
65 | }
66 | return result;
67 | }
68 |
69 | #pragma mark EXIF orientation tag converter
70 | // Convert an EXIF image orientation to an iOS one.
71 | // reference see here: http://sylvana.net/jpegcrop/exif_orientation.html
72 | + (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation {
73 | UIImageOrientation orientation = UIImageOrientationUp;
74 | switch (exifOrientation) {
75 | case 1:
76 | orientation = UIImageOrientationUp;
77 | break;
78 |
79 | case 3:
80 | orientation = UIImageOrientationDown;
81 | break;
82 |
83 | case 8:
84 | orientation = UIImageOrientationLeft;
85 | break;
86 |
87 | case 6:
88 | orientation = UIImageOrientationRight;
89 | break;
90 |
91 | case 2:
92 | orientation = UIImageOrientationUpMirrored;
93 | break;
94 |
95 | case 4:
96 | orientation = UIImageOrientationDownMirrored;
97 | break;
98 |
99 | case 5:
100 | orientation = UIImageOrientationLeftMirrored;
101 | break;
102 |
103 | case 7:
104 | orientation = UIImageOrientationRightMirrored;
105 | break;
106 | default:
107 | break;
108 | }
109 | return orientation;
110 | }
111 |
112 |
113 |
114 | @end
115 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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
10 | #import "SDWebImageCompat.h"
11 | #import "SDWebImageManager.h"
12 |
13 | /**
14 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state.
15 | */
16 | @interface UIImageView (HighlightedWebCache)
17 |
18 | /**
19 | * Set the imageView `highlightedImage` with an `url`.
20 | *
21 | * The download is asynchronous and cached.
22 | *
23 | * @param url The url for the image.
24 | */
25 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url;
26 |
27 | /**
28 | * Set the imageView `highlightedImage` with an `url` and custom options.
29 | *
30 | * The download is asynchronous and cached.
31 | *
32 | * @param url The url for the image.
33 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
34 | */
35 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options;
36 |
37 | /**
38 | * Set the imageView `highlightedImage` with an `url`.
39 | *
40 | * The download is asynchronous and cached.
41 | *
42 | * @param url The url for the image.
43 | * @param completedBlock A block called when operation has been completed. This block has no return value
44 | * and takes the requested UIImage as first parameter. In case of error the image parameter
45 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
46 | * indicating if the image was retrived from the local cache or from the network.
47 | * The fourth parameter is the original image url.
48 | */
49 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock;
50 |
51 | /**
52 | * Set the imageView `highlightedImage` with an `url` and custom options.
53 | *
54 | * The download is asynchronous and cached.
55 | *
56 | * @param url The url for the image.
57 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
58 | * @param completedBlock A block called when operation has been completed. This block has no return value
59 | * and takes the requested UIImage as first parameter. In case of error the image parameter
60 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
61 | * indicating if the image was retrived from the local cache or from the network.
62 | * The fourth parameter is the original image url.
63 | */
64 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
65 |
66 | /**
67 | * Set the imageView `highlightedImage` with an `url` and custom options.
68 | *
69 | * The download is asynchronous and cached.
70 | *
71 | * @param url The url for the image.
72 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
73 | * @param progressBlock A block called while image is downloading
74 | * @param completedBlock A block called when operation has been completed. This block has no return value
75 | * and takes the requested UIImage as first parameter. In case of error the image parameter
76 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
77 | * indicating if the image was retrived from the local cache or from the network.
78 | * The fourth parameter is the original image url.
79 | */
80 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
81 |
82 | /**
83 | * Cancel the current download
84 | */
85 | - (void)sd_cancelCurrentHighlightedImageLoad;
86 |
87 | @end
88 |
89 |
90 | @interface UIImageView (HighlightedWebCacheDeprecated)
91 |
92 | - (void)setHighlightedImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:`");
93 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:`");
94 | - (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:completed:`");
95 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:completed:`");
96 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:progress:completed:`");
97 |
98 | - (void)cancelCurrentHighlightedImageLoad __deprecated_msg("Use `sd_cancelCurrentHighlightedImageLoad`");
99 |
100 | @end
101 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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 | #import "UIView+WebCacheOperation.h"
11 |
12 | #define UIImageViewHighlightedWebCacheOperationKey @"highlightedImage"
13 |
14 | @implementation UIImageView (HighlightedWebCache)
15 |
16 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url {
17 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil];
18 | }
19 |
20 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options {
21 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil];
22 | }
23 |
24 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock {
25 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock];
26 | }
27 |
28 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
29 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock];
30 | }
31 |
32 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
33 | [self sd_cancelCurrentHighlightedImageLoad];
34 |
35 | if (url) {
36 | __weak UIImageView *wself = self;
37 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
38 | if (!wself) return;
39 | dispatch_main_sync_safe (^
40 | {
41 | if (!wself) return;
42 | if (image) {
43 | wself.highlightedImage = image;
44 | [wself setNeedsLayout];
45 | }
46 | if (completedBlock && finished) {
47 | completedBlock(image, error, cacheType, url);
48 | }
49 | });
50 | }];
51 | [self sd_setImageLoadOperation:operation forKey:UIImageViewHighlightedWebCacheOperationKey];
52 | } else {
53 | dispatch_main_async_safe(^{
54 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
55 | if (completedBlock) {
56 | completedBlock(nil, error, SDImageCacheTypeNone, url);
57 | }
58 | });
59 | }
60 | }
61 |
62 | - (void)sd_cancelCurrentHighlightedImageLoad {
63 | [self sd_cancelImageLoadOperationWithKey:UIImageViewHighlightedWebCacheOperationKey];
64 | }
65 |
66 | @end
67 |
68 |
69 | @implementation UIImageView (HighlightedWebCacheDeprecated)
70 |
71 | - (void)setHighlightedImageWithURL:(NSURL *)url {
72 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil];
73 | }
74 |
75 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options {
76 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil];
77 | }
78 |
79 | - (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock {
80 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
81 | if (completedBlock) {
82 | completedBlock(image, error, cacheType);
83 | }
84 | }];
85 | }
86 |
87 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
88 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
89 | if (completedBlock) {
90 | completedBlock(image, error, cacheType);
91 | }
92 | }];
93 | }
94 |
95 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock {
96 | [self sd_setHighlightedImageWithURL:url options:0 progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
97 | if (completedBlock) {
98 | completedBlock(image, error, cacheType);
99 | }
100 | }];
101 | }
102 |
103 | - (void)cancelCurrentHighlightedImageLoad {
104 | [self sd_cancelCurrentHighlightedImageLoad];
105 | }
106 |
107 | @end
108 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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 | #import "SDWebImageManager.h"
11 |
12 | /**
13 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView.
14 | *
15 | * Usage with a UITableViewCell sub-class:
16 | *
17 | * @code
18 |
19 | #import
20 |
21 | ...
22 |
23 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
24 | {
25 | static NSString *MyIdentifier = @"MyIdentifier";
26 |
27 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
28 |
29 | if (cell == nil) {
30 | cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier]
31 | autorelease];
32 | }
33 |
34 | // Here we use the provided sd_setImageWithURL: method to load the web image
35 | // Ensure you use a placeholder image otherwise cells will be initialized with no image
36 | [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"]
37 | placeholderImage:[UIImage imageNamed:@"placeholder"]];
38 |
39 | cell.textLabel.text = @"My Text";
40 | return cell;
41 | }
42 |
43 | * @endcode
44 | */
45 | @interface UIImageView (WebCache)
46 |
47 | /**
48 | * Get the current image URL.
49 | *
50 | * Note that because of the limitations of categories this property can get out of sync
51 | * if you use sd_setImage: directly.
52 | */
53 | - (NSURL *)sd_imageURL;
54 |
55 | /**
56 | * Set the imageView `image` with an `url`.
57 | *
58 | * The download is asynchronous and cached.
59 | *
60 | * @param url The url for the image.
61 | */
62 | - (void)sd_setImageWithURL:(NSURL *)url;
63 |
64 | /**
65 | * Set the imageView `image` with an `url` and a placeholder.
66 | *
67 | * The download is asynchronous and cached.
68 | *
69 | * @param url The url for the image.
70 | * @param placeholder The image to be set initially, until the image request finishes.
71 | * @see sd_setImageWithURL:placeholderImage:options:
72 | */
73 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;
74 |
75 | /**
76 | * Set the imageView `image` with an `url`, placeholder and custom options.
77 | *
78 | * The download is asynchronous and cached.
79 | *
80 | * @param url The url for the image.
81 | * @param placeholder The image to be set initially, until the image request finishes.
82 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
83 | */
84 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
85 |
86 | /**
87 | * Set the imageView `image` with an `url`.
88 | *
89 | * The download is asynchronous and cached.
90 | *
91 | * @param url The url for the image.
92 | * @param completedBlock A block called when operation has been completed. This block has no return value
93 | * and takes the requested UIImage as first parameter. In case of error the image parameter
94 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
95 | * indicating if the image was retrived from the local cache or from the network.
96 | * The fourth parameter is the original image url.
97 | */
98 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock;
99 |
100 | /**
101 | * Set the imageView `image` with an `url`, placeholder.
102 | *
103 | * The download is asynchronous and cached.
104 | *
105 | * @param url The url for the image.
106 | * @param placeholder The image to be set initially, until the image request finishes.
107 | * @param completedBlock A block called when operation has been completed. This block has no return value
108 | * and takes the requested UIImage as first parameter. In case of error the image parameter
109 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
110 | * indicating if the image was retrived from the local cache or from the network.
111 | * The fourth parameter is the original image url.
112 | */
113 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
114 |
115 | /**
116 | * Set the imageView `image` with an `url`, placeholder and custom options.
117 | *
118 | * The download is asynchronous and cached.
119 | *
120 | * @param url The url for the image.
121 | * @param placeholder The image to be set initially, until the image request finishes.
122 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
123 | * @param completedBlock A block called when operation has been completed. This block has no return value
124 | * and takes the requested UIImage as first parameter. In case of error the image parameter
125 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
126 | * indicating if the image was retrived from the local cache or from the network.
127 | * The fourth parameter is the original image url.
128 | */
129 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
130 |
131 | /**
132 | * Set the imageView `image` with an `url`, placeholder and custom options.
133 | *
134 | * The download is asynchronous and cached.
135 | *
136 | * @param url The url for the image.
137 | * @param placeholder The image to be set initially, until the image request finishes.
138 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
139 | * @param progressBlock A block called while image is downloading
140 | * @param completedBlock A block called when operation has been completed. This block has no return value
141 | * and takes the requested UIImage as first parameter. In case of error the image parameter
142 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
143 | * indicating if the image was retrived from the local cache or from the network.
144 | * The fourth parameter is the original image url.
145 | */
146 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
147 |
148 | /**
149 | * Set the imageView `image` with an `url` and a optionaly placeholder image.
150 | *
151 | * The download is asynchronous and cached.
152 | *
153 | * @param url The url for the image.
154 | * @param placeholder The image to be set initially, until the image request finishes.
155 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
156 | * @param progressBlock A block called while image is downloading
157 | * @param completedBlock A block called when operation has been completed. This block has no return value
158 | * and takes the requested UIImage as first parameter. In case of error the image parameter
159 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
160 | * indicating if the image was retrived from the local cache or from the network.
161 | * The fourth parameter is the original image url.
162 | */
163 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
164 |
165 | /**
166 | * Download an array of images and starts them in an animation loop
167 | *
168 | * @param arrayOfURLs An array of NSURL
169 | */
170 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs;
171 |
172 | /**
173 | * Cancel the current download
174 | */
175 | - (void)sd_cancelCurrentImageLoad;
176 |
177 | - (void)sd_cancelCurrentAnimationImagesLoad;
178 |
179 | @end
180 |
181 |
182 | @interface UIImageView (WebCacheDeprecated)
183 |
184 | - (NSURL *)imageURL __deprecated_msg("Use `sd_imageURL`");
185 |
186 | - (void)setImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:`");
187 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:`");
188 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options`");
189 |
190 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:completed:`");
191 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:completed:`");
192 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:completed:`");
193 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:progress:completed:`");
194 |
195 | - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs __deprecated_msg("Use `sd_setAnimationImagesWithURLs:`");
196 |
197 | - (void)cancelCurrentArrayLoad __deprecated_msg("Use `sd_cancelCurrentAnimationImagesLoad`");
198 |
199 | - (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelCurrentImageLoad`");
200 |
201 | @end
202 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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 | #import "objc/runtime.h"
11 | #import "UIView+WebCacheOperation.h"
12 |
13 | static char imageURLKey;
14 |
15 | @implementation UIImageView (WebCache)
16 |
17 | - (void)sd_setImageWithURL:(NSURL *)url {
18 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
19 | }
20 |
21 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
22 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil];
23 | }
24 |
25 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
26 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil];
27 | }
28 |
29 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock {
30 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock];
31 | }
32 |
33 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
34 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock];
35 | }
36 |
37 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
38 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock];
39 | }
40 |
41 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
42 | [self sd_cancelCurrentImageLoad];
43 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
44 |
45 | if (!(options & SDWebImageDelayPlaceholder)) {
46 | dispatch_main_async_safe(^{
47 | self.image = placeholder;
48 | });
49 | }
50 |
51 | if (url) {
52 | __weak UIImageView *wself = self;
53 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
54 | if (!wself) return;
55 | dispatch_main_sync_safe(^{
56 | if (!wself) return;
57 | if (image) {
58 | wself.image = image;
59 | [wself setNeedsLayout];
60 | } else {
61 | if ((options & SDWebImageDelayPlaceholder)) {
62 | wself.image = placeholder;
63 | [wself setNeedsLayout];
64 | }
65 | }
66 | if (completedBlock && finished) {
67 | completedBlock(image, error, cacheType, url);
68 | }
69 | });
70 | }];
71 | [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"];
72 | } else {
73 | dispatch_main_async_safe(^{
74 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
75 | if (completedBlock) {
76 | completedBlock(nil, error, SDImageCacheTypeNone, url);
77 | }
78 | });
79 | }
80 | }
81 |
82 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
83 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url];
84 | UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key];
85 |
86 | [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock];
87 | }
88 |
89 | - (NSURL *)sd_imageURL {
90 | return objc_getAssociatedObject(self, &imageURLKey);
91 | }
92 |
93 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs {
94 | [self sd_cancelCurrentAnimationImagesLoad];
95 | __weak UIImageView *wself = self;
96 |
97 | NSMutableArray *operationsArray = [[NSMutableArray alloc] init];
98 |
99 | for (NSURL *logoImageURL in arrayOfURLs) {
100 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
101 | if (!wself) return;
102 | dispatch_main_sync_safe(^{
103 | __strong UIImageView *sself = wself;
104 | [sself stopAnimating];
105 | if (sself && image) {
106 | NSMutableArray *currentImages = [[sself animationImages] mutableCopy];
107 | if (!currentImages) {
108 | currentImages = [[NSMutableArray alloc] init];
109 | }
110 | [currentImages addObject:image];
111 |
112 | sself.animationImages = currentImages;
113 | [sself setNeedsLayout];
114 | }
115 | [sself startAnimating];
116 | });
117 | }];
118 | [operationsArray addObject:operation];
119 | }
120 |
121 | [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"];
122 | }
123 |
124 | - (void)sd_cancelCurrentImageLoad {
125 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"];
126 | }
127 |
128 | - (void)sd_cancelCurrentAnimationImagesLoad {
129 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"];
130 | }
131 |
132 | @end
133 |
134 |
135 | @implementation UIImageView (WebCacheDeprecated)
136 |
137 | - (NSURL *)imageURL {
138 | return [self sd_imageURL];
139 | }
140 |
141 | - (void)setImageWithURL:(NSURL *)url {
142 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
143 | }
144 |
145 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
146 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil];
147 | }
148 |
149 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
150 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil];
151 | }
152 |
153 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock {
154 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
155 | if (completedBlock) {
156 | completedBlock(image, error, cacheType);
157 | }
158 | }];
159 | }
160 |
161 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock {
162 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
163 | if (completedBlock) {
164 | completedBlock(image, error, cacheType);
165 | }
166 | }];
167 | }
168 |
169 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
170 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
171 | if (completedBlock) {
172 | completedBlock(image, error, cacheType);
173 | }
174 | }];
175 | }
176 |
177 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock {
178 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
179 | if (completedBlock) {
180 | completedBlock(image, error, cacheType);
181 | }
182 | }];
183 | }
184 |
185 | - (void)cancelCurrentArrayLoad {
186 | [self sd_cancelCurrentAnimationImagesLoad];
187 | }
188 |
189 | - (void)cancelCurrentImageLoad {
190 | [self sd_cancelCurrentImageLoad];
191 | }
192 |
193 | - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs {
194 | [self sd_setAnimationImagesWithURLs:arrayOfURLs];
195 | }
196 |
197 | @end
198 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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
10 | #import "SDWebImageManager.h"
11 |
12 | @interface UIView (WebCacheOperation)
13 |
14 | /**
15 | * Set the image load operation (storage in a UIView based dictionary)
16 | *
17 | * @param operation the operation
18 | * @param key key for storing the operation
19 | */
20 | - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key;
21 |
22 | /**
23 | * Cancel all operations for the current UIView and key
24 | *
25 | * @param key key for identifying the operations
26 | */
27 | - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key;
28 |
29 | /**
30 | * Just remove the operations corresponding to the current UIView and key without cancelling them
31 | *
32 | * @param key key for identifying the operations
33 | */
34 | - (void)sd_removeImageLoadOperationWithKey:(NSString *)key;
35 |
36 | @end
37 |
--------------------------------------------------------------------------------
/WaterFlowLayout/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 | #import "objc/runtime.h"
11 |
12 | static char loadOperationKey;
13 |
14 | @implementation UIView (WebCacheOperation)
15 |
16 | - (NSMutableDictionary *)operationDictionary {
17 | NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
18 | if (operations) {
19 | return operations;
20 | }
21 | operations = [NSMutableDictionary dictionary];
22 | objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
23 | return operations;
24 | }
25 |
26 | - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key {
27 | [self sd_cancelImageLoadOperationWithKey:key];
28 | NSMutableDictionary *operationDictionary = [self operationDictionary];
29 | [operationDictionary setObject:operation forKey:key];
30 | }
31 |
32 | - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key {
33 | // Cancel in progress downloader from queue
34 | NSMutableDictionary *operationDictionary = [self operationDictionary];
35 | id operations = [operationDictionary objectForKey:key];
36 | if (operations) {
37 | if ([operations isKindOfClass:[NSArray class]]) {
38 | for (id operation in operations) {
39 | if (operation) {
40 | [operation cancel];
41 | }
42 | }
43 | } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){
44 | [(id) operations cancel];
45 | }
46 | [operationDictionary removeObjectForKey:key];
47 | }
48 | }
49 |
50 | - (void)sd_removeImageLoadOperationWithKey:(NSString *)key {
51 | NSMutableDictionary *operationDictionary = [self operationDictionary];
52 | [operationDictionary removeObjectForKey:key];
53 | }
54 |
55 | @end
56 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPBlankView/SPBlankView.h:
--------------------------------------------------------------------------------
1 | //
2 | // SPBlankView.h
3 | // SPScrollViewTest
4 | //
5 | // Created by Tree on 2017/7/6.
6 | // Copyright © 2017年 TR2E. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface SPBlankView : UIView
12 |
13 | @property (nonatomic, copy) NSString *blankTipString;
14 | @property (nonatomic, copy) NSString *blankImgName;
15 |
16 | @end
17 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPBlankView/SPBlankView.m:
--------------------------------------------------------------------------------
1 | //
2 | // SPBlankView.m
3 | // SPScrollViewTest
4 | //
5 | // Created by Tree on 2017/7/6.
6 | // Copyright © 2017年 TR2E. All rights reserved.
7 | //
8 |
9 | #import "SPBlankView.h"
10 |
11 | @interface SPBlankView()
12 | @property (nonatomic, strong) UILabel *blankTipLabel;
13 | @property (nonatomic, strong) UIImageView *blankImgView;
14 | @end
15 |
16 | @implementation SPBlankView
17 |
18 | - (instancetype)init{
19 | if (self = [super init]) {
20 | [self initializeUI];
21 | }
22 | return self;
23 | }
24 |
25 | - (instancetype)initWithFrame:(CGRect)frame{
26 | if (self = [super initWithFrame:frame]) {
27 | [self initializeUI];
28 | }
29 | return self;
30 | }
31 |
32 | - (void)initializeUI{
33 |
34 | UIImage *image = [UIImage imageNamed:@"sp_blank"];
35 | UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
36 | [imageView sizeToFit];
37 | [self addSubview:imageView];
38 | self.blankImgView = imageView;
39 |
40 | UILabel *label = [[UILabel alloc] init];
41 | label.textAlignment = NSTextAlignmentCenter;
42 | label.text = @"暂无内容";
43 | label.font = [UIFont systemFontOfSize:15 weight:UIFontWeightThin];
44 | label.textColor = [UIColor colorWithRed:172/255.0 green:172/255.0 blue:172/255.0 alpha:1];
45 | [label sizeToFit];
46 | [self addSubview:label];
47 | self.blankTipLabel = label;
48 |
49 | }
50 |
51 | - (void)setBlankImgName:(NSString *)blankImgName{
52 | _blankImgName = blankImgName;
53 | self.blankImgView.image = [UIImage imageNamed:blankImgName];
54 | [self.blankImgView sizeToFit];
55 | }
56 |
57 | - (void)setBlankTipString:(NSString *)blankTipString{
58 | _blankTipString = blankTipString;
59 | self.blankTipLabel.text = blankTipString;
60 | [self.blankTipLabel sizeToFit];
61 | }
62 |
63 | - (void)layoutSubviews{
64 | [super layoutSubviews];
65 |
66 | self.blankImgView.center = CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0 - 40);
67 | self.blankTipLabel.center = CGPointMake(CGRectGetMidX(_blankImgView.frame), CGRectGetMaxY(_blankImgView.frame) + _blankTipLabel.frame.size.height/2 + 20);
68 |
69 | }
70 |
71 | @end
72 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPCategories/UICollectionView+SPEasyLoading.h:
--------------------------------------------------------------------------------
1 | //
2 | // UICollectionView+SPEasyLoading.h
3 | // SPScrollViewTest
4 | //
5 | // Created by Tree on 2017/7/6.
6 | // Copyright © 2017年 TR2E. All rights reserved.
7 | //
8 |
9 | #import
10 | #import "UIScrollView+SPEasyLoading.h"
11 |
12 | @interface UICollectionView (SPEasyLoading)
13 |
14 | @end
15 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPCategories/UICollectionView+SPEasyLoading.m:
--------------------------------------------------------------------------------
1 | //
2 | // UICollectionView+SPEasyLoading.m
3 | // SPScrollViewTest
4 | //
5 | // Created by Tree on 2017/7/6.
6 | // Copyright © 2017年 TR2E. All rights reserved.
7 | //
8 |
9 | #import "UICollectionView+SPEasyLoading.h"
10 | #import "SPLoadMoreView.h"
11 | #import "SPBlankView.h"
12 | #import
13 | #import "SPEasyLoadingHeader.h"
14 |
15 | @implementation UICollectionView (SPEasyLoading)
16 |
17 | void sp_collectionView_instanceMethod_Swizzle(Class c,SEL orig,SEL news){
18 |
19 | Method origMethod = class_getInstanceMethod(c, orig);
20 | Method newMethod = class_getInstanceMethod(c, news);
21 |
22 | if (class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
23 | class_replaceMethod(c, news, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
24 | else
25 | method_exchangeImplementations(origMethod, newMethod);
26 |
27 | }
28 |
29 |
30 | + (void)load{
31 | sp_collectionView_instanceMethod_Swizzle(self, @selector(reloadData), @selector(sp_collectionView_reloadData));
32 | sp_collectionView_instanceMethod_Swizzle(self, @selector(reloadSections:), @selector(sp_collectionView_reloadSections:));
33 | }
34 |
35 | - (void)sp_dealloc{
36 | [self sp_dealloc];
37 | if (self.canRefresh) {
38 | [self removeObserver:self forKeyPath:k_contentOffset];
39 | }
40 | if (self.canLoadMore) {
41 | [self removeObserver:self forKeyPath:k_contentSize];
42 | }
43 | }
44 |
45 | - (void)sp_collectionView_reloadData{
46 | [self sp_collectionView_reloadData];
47 |
48 | // more view
49 | if (self.pageSize != 0)
50 | {
51 | if (self.sp_datas.count < self.pageSize)
52 | {
53 | [self showMoreView:NO];
54 | }
55 | else
56 | {
57 | [self showMoreView:YES];
58 | }
59 | }
60 |
61 | }
62 |
63 | - (void)sp_collectionView_reloadSections:(NSIndexSet *)sections{
64 | [self sp_collectionView_reloadSections:sections];
65 |
66 | // more view
67 | if (self.pageSize != 0)
68 | {
69 | if (self.sp_datas.count < self.pageSize)
70 | {
71 | [self showMoreView:NO];
72 | }
73 | else
74 | {
75 | [self showMoreView:YES];
76 | }
77 | }
78 |
79 | }
80 |
81 | - (void)showMoreView:(BOOL) show{
82 |
83 | if (!self.canLoadMore) return;
84 | self.sp_loadMoreView.hidden = !show;
85 |
86 | }
87 |
88 | @end
89 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPCategories/UIScrollView+SPEasyLoading.h:
--------------------------------------------------------------------------------
1 | //
2 | // UIScrollView+SPEasyLoading.h
3 | // SPScrollViewTest
4 | //
5 | // Created by Tree on 2017/7/6.
6 | // Copyright © 2017年 TR2E. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @class SPLoadMoreView;
12 | @class SPRefreshControl;
13 |
14 | @interface UIView (SPEasyLoading)
15 | @property (nonatomic, strong) NSMutableArray *sp_datas;
16 | @end
17 |
18 | @interface UIScrollView (SPEasyLoading)
19 |
20 | // load part
21 | @property (nonatomic, strong) SPLoadMoreView *sp_loadMoreView;
22 | @property (nonatomic, strong) SPRefreshControl *sp_refreshControl;
23 |
24 | // blank part
25 | @property (nonatomic, assign) BOOL needBlankView;// default is NO
26 | @property (nonatomic, strong) UIView *blankView;
27 | @property (nonatomic, copy) NSString *blankImgName;
28 | @property (nonatomic, copy) NSString *blankTips;
29 |
30 | // data part
31 | @property (nonatomic, assign) NSInteger pageSize;
32 |
33 | // call back
34 | @property (nonatomic, copy) dispatch_block_t loadMoreDataCallBack;
35 | @property (nonatomic, copy) dispatch_block_t refreshDataCallBack;
36 |
37 | // current loading state
38 | @property (nonatomic, assign) BOOL loading;
39 |
40 | // pull to refresh, default is NO
41 | @property (nonatomic, assign) BOOL canRefresh;
42 |
43 | // push to refresh, default is NO
44 | @property (nonatomic, assign) BOOL canLoadMore;
45 | // push to refresh, when scroll to bottom,load more automatically,default is NO
46 | @property (nonatomic, assign) BOOL canAutoLoadMore;
47 |
48 | // action part
49 | - (void)beginNonAnimateRefreshing;
50 | - (void)beginAnimateRefreshing;
51 | - (void)doneLoadDatas;
52 |
53 | @end
54 |
55 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPCategories/UIScrollView+SPEasyLoading.m:
--------------------------------------------------------------------------------
1 | //
2 | // UIScrollView+SPEasyLoading.m
3 | // SPScrollViewTest
4 | //
5 | // Created by Tree on 2017/7/6.
6 | // Copyright © 2017年 TR2E. All rights reserved.
7 | //
8 |
9 | #import "UIScrollView+SPEasyLoading.h"
10 | #import "SPEasyLoadingHeader.h"
11 | #import "SPLoadMoreView.h"
12 | #import "SPRefreshControl.h"
13 | #import "SPBlankView.h"
14 | #import
15 |
16 | //------------ iPhone X ------------
17 | #define DEVICE_IS_IPHONEX [UIScreen mainScreen].bounds.size.height == 812
18 |
19 | // the strange thing is that when we use self.frame before layoutsubviews
20 | // the value always based on 375(the width of 4.7' screen)
21 | // so we must calculate the ratio manually to make sure the width is correct
22 | #define SCREENRATIO [UIScreen mainScreen].bounds.size.width/375.0
23 |
24 | static char AssociateDatasKey;
25 | static char AssociateCanRefreshKey;
26 | static char AssociateCanLoadMoreKey;
27 | static char AssociateCanAutoLoadMoreKey;
28 | static char AssociateRefreshControlKey;
29 | static char AssociateMoreViewKey;
30 | static char AssociatePageSizeKey;
31 | static char AssociateRefreshDataBlockKey;
32 | static char AssociateLoadMoreDataBlockKey;
33 | static char AssociateLoadingStateKey;
34 | static char AssociateBlankViewKey;
35 | static char AssociateNeedBlankViewKey;
36 | static char AssociateNeedBlankImgKey;
37 | static char AssociateNeedBlankTipsKey;
38 |
39 | @implementation UIView (SPEasyLoading)
40 | @dynamic sp_datas;
41 |
42 | - (NSMutableArray *)sp_datas{
43 | id datas = objc_getAssociatedObject(self, &AssociateDatasKey);
44 | if (!datas) {
45 | datas = [NSMutableArray array];
46 | objc_setAssociatedObject (self, &AssociateDatasKey,datas,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
47 | }
48 | return datas;
49 | }
50 |
51 | - (void)setSp_datas:(NSMutableArray *)sp_datas{
52 | objc_setAssociatedObject (self, &AssociateDatasKey,sp_datas,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
53 | }
54 |
55 | @end
56 |
57 | @implementation UIScrollView (SPEasyLoading)
58 |
59 | @dynamic pageSize;
60 | @dynamic loading;
61 | @dynamic blankView;
62 | @dynamic canRefresh;
63 | @dynamic canLoadMore;
64 | @dynamic needBlankView;
65 | @dynamic canAutoLoadMore;
66 | @dynamic sp_loadMoreView;
67 | @dynamic sp_refreshControl;
68 | @dynamic refreshDataCallBack;
69 | @dynamic loadMoreDataCallBack;
70 | @dynamic blankImgName;
71 | @dynamic blankTips;
72 |
73 |
74 | #pragma mark - initialize ui
75 | // 初始化refreshControl
76 | - (void)initializeRefreshControl{
77 |
78 | if (!self.sp_refreshControl)
79 | {
80 | self.sp_refreshControl = [[SPRefreshControl alloc] initWithFrame:
81 | CGRectMake(0, -refreshControlHeight, self.frame.size.width, refreshControlHeight)];
82 |
83 | __weak typeof(self) ws = self;
84 | self.sp_refreshControl.refreshControlisRefreshing = ^(BOOL isRefreshing) {
85 | ws.loading = isRefreshing;
86 | };
87 |
88 | [self.sp_refreshControl addTarget:self action:@selector(refreshControlAction:) forControlEvents:UIControlEventValueChanged];
89 |
90 | [self addSubview:self.sp_refreshControl];
91 | }
92 |
93 | }
94 |
95 | // 初始化loadmoreView
96 | - (void)initializeLoadMoreView{
97 |
98 | if (!self.sp_loadMoreView) {
99 |
100 | self.sp_loadMoreView = [[SPLoadMoreView alloc] initWithFrame:
101 | CGRectMake(0, self.contentSize.height, self.frame.size.width, moreViewHeight)];
102 |
103 | __weak typeof(self) ws = self;
104 | self.sp_loadMoreView.loadMoreisRefreshing = ^(BOOL isRefreshing) {
105 | ws.loading = isRefreshing;
106 | };
107 |
108 | self.loadMoreDataCallBack = self.sp_loadMoreView.doLoadMoreCallBack;
109 |
110 | self.sp_loadMoreView.canAutoLoadMore = self.canAutoLoadMore;
111 |
112 | [self addSubview:self.sp_loadMoreView];
113 |
114 | }
115 |
116 | }
117 |
118 | #pragma mark - action part
119 | // action part
120 | - (void)beginNonAnimateRefreshing{
121 | self.sp_refreshControl.refreshState = SPRefreshStateNonAnimateRefreshing;
122 | }
123 |
124 | - (void)beginAnimateRefreshing{
125 | self.sp_refreshControl.refreshState = SPRefreshStateRefreshing;
126 | }
127 |
128 | - (void)doneLoadDatas{
129 | self.sp_refreshControl.refreshState = SPRefreshStateNormal;
130 |
131 | // blank view
132 | [self handleBlankView];
133 |
134 | if (!self.sp_loadMoreView) return;
135 | if (self.sp_datas.count < self.pageSize)
136 | {
137 | self.sp_loadMoreView.loadMoreState = SPLoadMoreStateNonFullPage;
138 | }
139 | else
140 | {
141 | NSInteger flag = self.sp_datas.count % self.pageSize;
142 | if (flag)
143 | {
144 | self.sp_loadMoreView.loadMoreState = SPLoadMoreStateHasNoMore;
145 | }
146 | else
147 | {
148 | self.sp_loadMoreView.loadMoreState = SPLoadMoreStateNormal;
149 | }
150 | }
151 | }
152 |
153 | #pragma mark - Refresh part
154 | // refresh call back
155 | - (void)refreshControlAction:(SPRefreshControl *)sender{
156 |
157 | self.refreshDataCallBack?self.refreshDataCallBack():nil;
158 |
159 | // 如果存在loadmoreview 将之前的状态清空
160 | if (self.sp_loadMoreView)
161 | {
162 | self.sp_loadMoreView.loadMoreState = SPLoadMoreStateNormal;
163 | }
164 |
165 | }
166 |
167 | - (void)handleBlankView{
168 |
169 | if (!self.needBlankView) {
170 | return;
171 | }
172 |
173 | // blank view
174 | if (!self.sp_datas.count) {
175 |
176 | if (self.blankView) {// 防止重复添加
177 | return;
178 | }
179 |
180 | self.blankView = [[SPBlankView alloc] initWithFrame:
181 | CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.width)];
182 | if (self.blankImgName) {
183 | ((SPBlankView *)self.blankView).blankImgName = self.blankImgName;
184 | }
185 | if (self.blankTips) {
186 | ((SPBlankView *)self.blankView).blankTipString = self.blankTips;
187 | }
188 | self.blankView.center = CGPointMake(self.bounds.size.width/2.0 - self.contentInset.left, self.bounds.size.height/2.0 - self.contentInset.top - (DEVICE_IS_IPHONEX?88:64));
189 | [self addSubview:self.blankView];
190 |
191 | }else{
192 | self.blankView.hidden = YES;
193 | [self.blankView removeFromSuperview];
194 | self.blankView = nil;
195 | }
196 | }
197 |
198 | - (void)showBlankViewWithLoading:(BOOL)loading{
199 | if (loading && self.blankView && self.needBlankView) {
200 | self.blankView.hidden = YES;
201 | [self.blankView removeFromSuperview];
202 | self.blankView = nil;
203 | }
204 | }
205 |
206 | #pragma mark - get/set
207 | - (void)setCanLoadMore:(BOOL)loadMore{
208 | objc_setAssociatedObject (self, &AssociateCanLoadMoreKey,@(loadMore),OBJC_ASSOCIATION_ASSIGN);
209 | if (loadMore) {
210 | [self initializeLoadMoreView];
211 | }else{
212 | self.sp_loadMoreView = nil;
213 | }
214 | }
215 |
216 |
217 |
218 | - (BOOL)canLoadMore{
219 | return [objc_getAssociatedObject(self, &AssociateCanLoadMoreKey) boolValue];
220 | }
221 |
222 | - (void)setCanAutoLoadMore:(BOOL)canAutoLoadMore{
223 | objc_setAssociatedObject (self, &AssociateCanAutoLoadMoreKey,@(canAutoLoadMore),OBJC_ASSOCIATION_ASSIGN);
224 | if (!self.canLoadMore) {
225 | self.canLoadMore = YES;
226 | }
227 | }
228 |
229 | - (BOOL)canAutoLoadMore{
230 | return objc_getAssociatedObject(self, &AssociateCanAutoLoadMoreKey);
231 | }
232 |
233 | - (void)setCanRefresh:(BOOL)canRefresh{
234 | objc_setAssociatedObject (self, &AssociateCanRefreshKey,@(canRefresh),OBJC_ASSOCIATION_ASSIGN);
235 | if (canRefresh) {
236 | [self initializeRefreshControl];
237 | }else {
238 | self.refreshControl = nil;
239 | }
240 | }
241 |
242 | - (BOOL)canRefresh{
243 | return [objc_getAssociatedObject(self, &AssociateCanRefreshKey) boolValue];
244 | }
245 |
246 | - (void)setLoading:(BOOL)loading{
247 | [self showBlankViewWithLoading:loading];
248 | objc_setAssociatedObject(self, &AssociateLoadingStateKey, @(loading), OBJC_ASSOCIATION_ASSIGN);
249 | }
250 |
251 | - (BOOL)loading{
252 | return [objc_getAssociatedObject(self, &AssociateLoadingStateKey) boolValue];
253 | }
254 |
255 |
256 | - (void)setRefreshDataCallBack:(dispatch_block_t)refreshDataCallBack{
257 | objc_setAssociatedObject (self, &AssociateRefreshDataBlockKey,refreshDataCallBack,OBJC_ASSOCIATION_COPY);
258 | }
259 |
260 | - (dispatch_block_t)refreshDataCallBack{
261 | return objc_getAssociatedObject(self,&AssociateRefreshDataBlockKey);
262 | }
263 |
264 | - (void)setLoadMoreDataCallBack:(dispatch_block_t)loadMoreDataCallBack{
265 | objc_setAssociatedObject (self, &AssociateLoadMoreDataBlockKey,loadMoreDataCallBack,OBJC_ASSOCIATION_COPY);
266 | SPLoadMoreView *moreView = objc_getAssociatedObject(self, &AssociateMoreViewKey);
267 | if (moreView) {
268 | moreView.doLoadMoreCallBack = loadMoreDataCallBack;
269 | }
270 | }
271 |
272 | - (dispatch_block_t)loadMoreDataCallBack{
273 | return objc_getAssociatedObject(self,&AssociateLoadMoreDataBlockKey);
274 | }
275 |
276 |
277 | - (void)setSp_refreshControl:(SPRefreshControl *)sp_refreshControl{
278 | objc_setAssociatedObject (self, &AssociateRefreshControlKey,sp_refreshControl,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
279 | }
280 |
281 | - (SPRefreshControl *)sp_refreshControl{
282 | return objc_getAssociatedObject(self, &AssociateRefreshControlKey) ;
283 | }
284 |
285 | - (SPLoadMoreView *)sp_loadMoreView{
286 | id moreView = objc_getAssociatedObject(self, &AssociateMoreViewKey);
287 | return moreView;
288 | }
289 |
290 | - (void)setSp_loadMoreView:(SPLoadMoreView *)sp_loadMoreView{
291 | objc_setAssociatedObject (self, &AssociateMoreViewKey,sp_loadMoreView,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
292 | }
293 |
294 | - (void)setPageSize:(NSInteger)pageSize{
295 | objc_setAssociatedObject (self, &AssociatePageSizeKey,@(pageSize),OBJC_ASSOCIATION_RETAIN_NONATOMIC);
296 | }
297 |
298 | - (NSInteger)pageSize{
299 | NSInteger size = [objc_getAssociatedObject(self, &AssociatePageSizeKey) integerValue];
300 | return size;
301 | }
302 |
303 | - (void)setBlankView:(UIView *)blankView{
304 | objc_setAssociatedObject(self, &AssociateBlankViewKey, blankView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
305 | }
306 |
307 | - (UIView *)blankView{
308 | UIView *blankView = objc_getAssociatedObject(self, &AssociateBlankViewKey);
309 | return blankView;
310 | }
311 |
312 | - (void)setNeedBlankView:(BOOL)needBlankView{
313 | objc_setAssociatedObject (self, &AssociateNeedBlankViewKey,@(needBlankView),OBJC_ASSOCIATION_ASSIGN);
314 | }
315 |
316 | - (BOOL)needBlankView{
317 | return [objc_getAssociatedObject(self, &AssociateNeedBlankViewKey) boolValue];
318 | }
319 |
320 | - (void)setBlankTips:(NSString *)blankTips{
321 | objc_setAssociatedObject(self, &AssociateNeedBlankTipsKey, blankTips, OBJC_ASSOCIATION_COPY);
322 | }
323 |
324 | - (NSString *)blankTips{
325 | return objc_getAssociatedObject(self, &AssociateNeedBlankTipsKey);
326 | }
327 |
328 | - (void)setBlankImgName:(NSString *)blankImgName{
329 | objc_setAssociatedObject(self, &AssociateNeedBlankImgKey, blankImgName, OBJC_ASSOCIATION_COPY);
330 | }
331 |
332 | - (NSString *)blankImgName{
333 | return objc_getAssociatedObject(self, &AssociateNeedBlankImgKey);
334 | }
335 |
336 | @end
337 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPEasyLoadingForCollectionView.h:
--------------------------------------------------------------------------------
1 | //
2 | // SPEasyLoadingForCollectionView.h
3 | // SPScrollViewTest
4 | //
5 | // Created by Tree on 2017/7/9.
6 | // Copyright © 2017年 TR2E. All rights reserved.
7 | //
8 |
9 | #ifndef SPEasyLoadingForCollectionView_h
10 | #define SPEasyLoadingForCollectionView_h
11 |
12 | #import "UICollectionView+SPEasyLoading.h"
13 | #import "SPRefreshControl.h"
14 | #import "SPLoadMoreView.h"
15 |
16 | #endif /* SPEasyLoadingForCollectionView_h */
17 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPEasyLoadingForTableView.h:
--------------------------------------------------------------------------------
1 | //
2 | // SPEasyLoadingForTableView.h
3 | // SPScrollViewTest
4 | //
5 | // Created by Tree on 2017/7/9.
6 | // Copyright © 2017年 TR2E. All rights reserved.
7 | //
8 |
9 | #ifndef SPEasyLoadingForTableView_h
10 | #define SPEasyLoadingForTableView_h
11 |
12 | #import "UITableView+SPHeightCache.h"
13 | #import "SPRefreshControl.h"
14 | #import "SPLoadMoreView.h"
15 |
16 | #endif /* SPEasyLoadingForTableView_h */
17 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPEasyLoadingHeader.h:
--------------------------------------------------------------------------------
1 | //
2 | // SPEasyLoadingHeader.h
3 | // uniclass
4 | //
5 | // Created by Tree on 2017/4/20.
6 | // Copyright © 2017年 uni-class. All rights reserved.
7 | //
8 |
9 | #ifndef SPEasyLoadingHeader_h
10 | #define SPEasyLoadingHeader_h
11 |
12 | static CGFloat moreViewHeight = 50;
13 | static CGFloat refreshControlHeight = 50;
14 |
15 | static NSString *const k_contentSize = @"contentSize";
16 | static NSString *const k_contentOffset = @"contentOffset";
17 |
18 | #endif /* SPEasyLoadingHeader_h */
19 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPHeightCache/UITableView+SPHeightCache.h:
--------------------------------------------------------------------------------
1 | //
2 | // UITableView+SPHeightCache.h
3 | // SPTableviewHelper
4 | //
5 | // Created by Tree on 2017/6/21.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import
10 | #import "UIScrollView+SPEasyLoading.h"
11 |
12 | @class SPHeightCache;
13 | @interface SPHeightCache : NSObject
14 |
15 | // Allow Cache Clear Automatically
16 | @property (nonatomic, assign) BOOL allowAutomaticOperation;
17 |
18 | // Cache Output
19 | - (CGFloat)heightCacheForIndexPath:(NSIndexPath *)indexPath;
20 |
21 | // Cache Input
22 | - (void)cacheHeight:(CGFloat)height forIndexPath:(NSIndexPath *)indexPath;
23 |
24 | // Cache Exist
25 | - (BOOL)cacheIsExistAtIndexPath:(NSIndexPath *)indexPath;
26 |
27 | // Cache Clear
28 | - (void)clearHeightCacheForIndexPath:(NSIndexPath *)indexPath;
29 | - (void)clearAllHeigthCaches;
30 |
31 | @end
32 |
33 | @interface UITableView (SPHeightCache)
34 |
35 | @property (nonatomic, strong) SPHeightCache *sp_heightCache;
36 |
37 | @end
38 |
39 | @interface UITableView (SPHeightCacheOperation)
40 |
41 | - (void)sp_reloadDataWithNoCacheClearOperation;
42 |
43 | @end
44 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPHeightCache/UITableView+SPTemplateLayoutCell.h:
--------------------------------------------------------------------------------
1 | //
2 | // UITableView+SPTemplateLayoutCell.h
3 | // SPTableviewHelper
4 | //
5 | // Created by Tree on 2017/6/22.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import
10 | #import "UITableView+SPHeightCache.h"
11 |
12 | @interface UITableView (SPTemplateLayoutCell)
13 |
14 | - (CGFloat)sp_heightForCellWithIdentifier:(NSString *)identifier configuration:(void(^)(id cell))configCell;
15 | - (CGFloat)sp_heightForCellWithIdentifier:(NSString *)identifier cacheByIndexPath:(NSIndexPath *)indexPath configuration:(void (^)(id cell))configCell;
16 | - (CGFloat)sp_systemCalculateCellHeightForTemplateCell:(UITableViewCell *)cell;
17 |
18 |
19 | @end
20 |
21 | @interface UITableViewCell (SPTemplateLayoutCell)
22 |
23 | @property (nonatomic, assign) BOOL sp_isTemplateLayoutCell;
24 |
25 | @end
26 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPHeightCache/UITableView+SPTemplateLayoutCell.m:
--------------------------------------------------------------------------------
1 | //
2 | // UITableView+SPTemplateLayoutCell.m
3 | // SPTableviewHelper
4 | //
5 | // Created by Tree on 2017/6/22.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import "UITableView+SPTemplateLayoutCell.h"
10 | #import
11 |
12 | static char AssociateTemplateCellDictionaryKey;
13 | typedef NSMutableDictionary SPTemplateCellDictionary;
14 |
15 | @implementation UITableView (SPTemplateLayoutCell)
16 |
17 | - (CGFloat)sp_heightForCellWithIdentifier:(NSString *)identifier configuration:(void (^)(id))configCell{
18 | NSAssert(identifier.length>0, @"must use an correct identifier to calculate the height");
19 | if (!identifier) return 0;
20 |
21 | UITableViewCell *templateLayoutCell = [self sp_templateCellForReuseIdentifier:identifier];
22 | [templateLayoutCell prepareForReuse];
23 |
24 | if (configCell) {
25 | configCell(templateLayoutCell);
26 | }
27 |
28 | return [self sp_systemCalculateCellHeightForTemplateCell:templateLayoutCell];
29 | }
30 |
31 | - (CGFloat)sp_heightForCellWithIdentifier:(NSString *)identifier cacheByIndexPath:(NSIndexPath *)indexPath configuration:(void (^)(id cell))configCell{
32 |
33 | if ([self.sp_heightCache cacheIsExistAtIndexPath:indexPath]) {
34 | NSLog(@"height from cache");
35 | return [self.sp_heightCache heightCacheForIndexPath:indexPath];
36 | }
37 |
38 | CGFloat height = [self sp_heightForCellWithIdentifier:identifier configuration:configCell];
39 | [self.sp_heightCache cacheHeight:height forIndexPath:indexPath];
40 | NSLog(@"height from calculating");
41 |
42 | return height;
43 |
44 | }
45 |
46 | - (CGFloat)sp_systemCalculateCellHeightForTemplateCell:(UITableViewCell *)cell{
47 | CGFloat contentWidth = CGRectGetWidth(cell.frame);
48 |
49 | CGRect cellbounds = cell.bounds;
50 | cellbounds.size.width = contentWidth;
51 | cell.bounds = cellbounds;
52 |
53 | CGFloat accessoryWidth = 0;
54 | if (cell.accessoryView) {
55 | accessoryWidth = 16 + CGRectGetWidth(cell.accessoryView.frame);
56 | }else{
57 | static const CGFloat systemAccessoryWidths[] = {
58 | [UITableViewCellAccessoryNone] = 0,
59 | [UITableViewCellAccessoryDisclosureIndicator] = 34,
60 | [UITableViewCellAccessoryDetailDisclosureButton] = 68,
61 | [UITableViewCellAccessoryCheckmark] = 40,
62 | [UITableViewCellAccessoryDetailButton] = 48
63 | };
64 | accessoryWidth = systemAccessoryWidths[cell.accessoryType];
65 | }
66 | contentWidth -= accessoryWidth;
67 |
68 | CGFloat calculateHeight = 0;
69 | if (contentWidth > 0) {
70 | NSLayoutConstraint *widthForceConstant = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:contentWidth];
71 |
72 | static BOOL isSystemVersionEqualOrGreaterThen10_2 = NO;
73 | static dispatch_once_t onceToken;
74 | dispatch_once(&onceToken, ^{
75 | isSystemVersionEqualOrGreaterThen10_2 = [UIDevice.currentDevice.systemVersion compare:@"10.2" options:NSNumericSearch] != NSOrderedAscending;
76 | });
77 |
78 | NSArray *edgeConstraints;
79 | if (isSystemVersionEqualOrGreaterThen10_2) {
80 | // To avoid conflicts, make width constraint softer than required (1000)
81 | widthForceConstant.priority = UILayoutPriorityRequired - 1;
82 |
83 | // Build edge constraints
84 | NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
85 | NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeRight multiplier:1.0 constant:accessoryWidth];
86 | NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
87 | NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
88 | edgeConstraints = @[leftConstraint, rightConstraint, topConstraint, bottomConstraint];
89 | [cell addConstraints:edgeConstraints];
90 | }
91 |
92 | // system calculate
93 | [cell.contentView addConstraint:widthForceConstant];
94 | calculateHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
95 |
96 | // clear constraint
97 | [cell.contentView removeConstraint:widthForceConstant];
98 | if (isSystemVersionEqualOrGreaterThen10_2) {
99 | [cell removeConstraints:edgeConstraints];
100 | }
101 | }
102 |
103 | if (calculateHeight == 0) {
104 | calculateHeight = 44;
105 | }
106 |
107 | if (self.separatorStyle != UITableViewCellSeparatorStyleNone) {
108 | calculateHeight += 1.0/[UIScreen mainScreen].scale;
109 | }
110 |
111 | return calculateHeight;
112 | }
113 |
114 | - (UITableViewCell *)sp_templateCellForReuseIdentifier:(NSString *)identifier{
115 |
116 | SPTemplateCellDictionary *templateCellDictionary = [self sp_templateCellDictionary];
117 |
118 | UITableViewCell *templateCell = templateCellDictionary[identifier];
119 | if (!templateCell) {
120 | templateCell = [self dequeueReusableCellWithIdentifier:identifier];
121 | templateCell.sp_isTemplateLayoutCell = YES;
122 | templateCell.contentView.translatesAutoresizingMaskIntoConstraints = NO;
123 | [templateCellDictionary setObject:templateCell forKey:identifier];
124 | }
125 |
126 | return templateCell;
127 | }
128 |
129 | - (SPTemplateCellDictionary *)sp_templateCellDictionary{
130 | SPTemplateCellDictionary *dict = objc_getAssociatedObject(self, &AssociateTemplateCellDictionaryKey);
131 | if (!dict) {
132 | dict = [NSMutableDictionary dictionary];
133 | objc_setAssociatedObject(self, &AssociateTemplateCellDictionaryKey, dict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
134 | }
135 | return dict;
136 | }
137 |
138 | @end
139 |
140 | static char AssociateIsTemplateLayoutCellKey;
141 | @implementation UITableViewCell (SPTemplateLayoutCell)
142 | @dynamic sp_isTemplateLayoutCell;
143 |
144 | - (void)setSp_isTemplateLayoutCell:(BOOL)sp_isTemplateLayoutCell{
145 | objc_setAssociatedObject(self, &AssociateIsTemplateLayoutCellKey, @(sp_isTemplateLayoutCell), OBJC_ASSOCIATION_ASSIGN);
146 | }
147 |
148 | - (BOOL)sp_isTemplateLayoutCell{
149 | return ((NSNumber *)objc_getAssociatedObject(self, &AssociateIsTemplateLayoutCellKey)).boolValue;
150 | }
151 |
152 | @end
153 |
154 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPRefreshView/SPLoadMoreView.h:
--------------------------------------------------------------------------------
1 | //
2 | // SPLoadMoreView.h
3 | // SPLoadingSystem
4 | //
5 | // Created by Tree on 2017/4/17.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | typedef NS_ENUM(NSInteger,SPLoadMoreState) {
12 |
13 | SPLoadMoreStateNormal = 1,
14 | SPLoadMoreStateRefreshing,
15 | SPLoadMoreStateHasNoMore,
16 | SPLoadMoreStateNonFullPage
17 |
18 | };
19 |
20 |
21 | @interface SPLoadMoreView : UIView
22 |
23 | // default is '显示更多...'
24 | @property (nonatomic, copy) NSString *noMoreString;
25 |
26 | // default is '-End-'
27 | @property (nonatomic, copy) NSString *moreString;
28 |
29 | // if it's YES,when scroll view scroll to bottom
30 | // change to RefreshingState automatically
31 | // default is NO
32 | @property (nonatomic, assign) BOOL canAutoLoadMore;
33 |
34 | // when the state is Refreshing,call this block automatically
35 | @property (nonatomic, copy) dispatch_block_t doLoadMoreCallBack;
36 |
37 | // current state
38 | @property (nonatomic, assign) SPLoadMoreState loadMoreState;
39 |
40 | // call this block to change the view's loading property
41 | @property (nonatomic, copy) void(^loadMoreisRefreshing)(BOOL isRefreshing);
42 |
43 | @end
44 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPRefreshView/SPLoadMoreView.m:
--------------------------------------------------------------------------------
1 | //
2 | // SPLoadMoreView.m
3 | // SPLoadingSystem
4 | //
5 | // Created by Tree on 2017/4/17.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import "SPLoadMoreView.h"
10 | #import "SPEasyLoadingHeader.h"
11 |
12 | @interface SPLoadMoreView(){
13 |
14 | BOOL _refreshingFlag;
15 | BOOL _isCollectionViewFlag;
16 |
17 | CGPoint _originalOffsets;
18 | CGFloat _conditionValue;
19 | UIEdgeInsets _originalInsets;
20 | CGRect _originalRefreshFrame;
21 |
22 | }
23 |
24 | @property (nonatomic, weak) UIScrollView *baseView;
25 | @property (nonatomic, strong) UIButton *loadBtn;
26 | @property (nonatomic, strong) UIActivityIndicatorView *activityView;
27 |
28 | @end
29 |
30 | @implementation SPLoadMoreView
31 |
32 | - (instancetype) initWithFrame:(CGRect)frame{
33 |
34 | if (self = [super initWithFrame:frame])
35 | {
36 | [self initializeMainViewWithFrame:frame];
37 | }
38 |
39 | return self;
40 |
41 | }
42 |
43 |
44 | - (void)initializeMainViewWithFrame:(CGRect)frame{
45 |
46 | // load more btn
47 | self.loadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
48 | _loadBtn.frame = CGRectMake(0, 0, frame.size.width-20, moreViewHeight);
49 | _loadBtn.center = self.center;
50 | _loadBtn.titleLabel.font = [UIFont systemFontOfSize:12];
51 | [_loadBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
52 | [_loadBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
53 | [_loadBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
54 | [_loadBtn addTarget:self action:@selector(loadMoreAction) forControlEvents:UIControlEventTouchUpInside];
55 |
56 |
57 | // activity
58 | self.activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
59 | _activityView.center = CGPointMake(frame.size.width - 25, _loadBtn.center.y);
60 |
61 | // tip
62 | self.moreString = _moreString.length?_moreString:@"显示更多...";
63 |
64 | // init state
65 | self.loadMoreState = SPLoadMoreStateNormal;
66 |
67 | //
68 | [self addSubview:_loadBtn];
69 | [self addSubview:_activityView];
70 |
71 | }
72 |
73 | - (void)willMoveToSuperview:(UIView *)newSuperview{
74 | [super willMoveToSuperview:newSuperview];
75 |
76 | if (newSuperview && ![newSuperview isKindOfClass:[UIScrollView class]]) return;
77 |
78 | [self.superview removeObserver:self forKeyPath:k_contentSize];
79 | if (_canAutoLoadMore) {
80 | [self.superview removeObserver:self forKeyPath:k_contentOffset];
81 | }
82 |
83 | if (newSuperview) {
84 | self.baseView = (UIScrollView *)newSuperview;
85 | }
86 |
87 | if ([newSuperview isKindOfClass:[UICollectionView class]]) {
88 | _isCollectionViewFlag = YES;
89 | }
90 |
91 | }
92 |
93 | - (void)layoutSubviews{
94 |
95 | if (_isCollectionViewFlag){
96 |
97 | self.frame = CGRectOffset(_originalRefreshFrame,
98 | -_baseView.contentInset.left,
99 | 0);
100 | }
101 |
102 | if(_loadMoreState == SPLoadMoreStateNormal)
103 | {
104 | _originalInsets = _baseView.contentInset;
105 | _originalOffsets = _baseView.contentOffset;
106 |
107 | UIEdgeInsets targetInset = UIEdgeInsetsMake(_originalInsets.top, _originalInsets.left, moreViewHeight, _originalInsets.right);
108 | _originalInsets = targetInset;
109 |
110 | _baseView.contentInset = targetInset;
111 |
112 | NSLog(@"loadmore content inset top:%f bottom:%f",_originalInsets.top,_originalInsets.bottom);
113 | }
114 |
115 | [super layoutSubviews];
116 | }
117 |
118 | #pragma mark - kvo
119 | - (void)setBaseView:(UIScrollView *)baseView{
120 | _baseView = baseView;
121 | [baseView addObserver:self forKeyPath:k_contentSize options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
122 | if (_canAutoLoadMore) {
123 | [baseView addObserver:self forKeyPath:k_contentOffset options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
124 | }
125 | }
126 |
127 | - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
128 | if ([keyPath isEqualToString:k_contentSize]) {
129 | //
130 | // id newChange = [change objectForKey:NSKeyValueChangeNewKey];// object for key / value for key
131 | // NSString *newChangeStr = [NSString stringWithFormat:@"%@",newChange];
132 | // CGSize contentSize = CGSizeFromString(newChangeStr);
133 | // NSLog(@"contentSize height---> %f",contentSize.height);
134 | [self changeLocationWithBaseView:_baseView];
135 |
136 | }
137 |
138 | if ([keyPath isEqualToString:k_contentOffset]) {
139 |
140 | [self changeAppearanceWithBaseView:_baseView];
141 |
142 | }
143 |
144 | }
145 |
146 | - (void)changeLocationWithBaseView:(UIScrollView *)baseView{
147 |
148 | CGFloat contentSizeHeight = baseView.contentSize.height;
149 | _originalRefreshFrame = self.frame = CGRectMake(self.frame.origin.x, contentSizeHeight, self.frame.size.width, self.frame.size.height);
150 |
151 | }
152 |
153 | - (void)changeAppearanceWithBaseView:(UIScrollView *)baseView{
154 |
155 | CGPoint contentOffset = baseView.contentOffset;
156 | CGFloat contentSizeHeight = baseView.contentSize.height + moreViewHeight;// canLoadmore时设置了inset
157 |
158 | if (contentOffset.y + _baseView.frame.size.height > contentSizeHeight) {
159 | if (baseView.isDragging && baseView.isDecelerating && !_refreshingFlag) {
160 | self.loadMoreState = SPLoadMoreStateRefreshing;
161 | }
162 | }
163 |
164 | }
165 |
166 | #pragma mark - Actions
167 | - (void)loadMoreAction{
168 | self.loadMoreState = SPLoadMoreStateRefreshing;
169 | }
170 |
171 | #pragma mark - Properties
172 |
173 | - (void)setCanAutoLoadMore:(BOOL)canAutoLoadMore{
174 | _canAutoLoadMore = canAutoLoadMore;
175 | }
176 |
177 | - (void)setLoadMoreState:(SPLoadMoreState)loadMoreState{
178 |
179 | BOOL isRefreshing = loadMoreState == SPLoadMoreStateRefreshing;
180 | self.loadMoreisRefreshing?self.loadMoreisRefreshing(isRefreshing):nil;
181 | if(loadMoreState == _loadMoreState) return;
182 | _loadMoreState = loadMoreState;
183 | [self updateAppearanceWithState:loadMoreState];
184 | }
185 |
186 | - (void)updateAppearanceWithState:(SPLoadMoreState)state{
187 |
188 | if (state == SPLoadMoreStateNonFullPage)
189 | {
190 | _refreshingFlag = NO;
191 |
192 | _loadBtn.hidden = YES;
193 | [_activityView stopAnimating];
194 | return;
195 | }
196 |
197 | _loadBtn.hidden = NO;
198 |
199 | if (state == SPLoadMoreStateRefreshing)
200 | {
201 | _refreshingFlag = YES;
202 |
203 | _loadBtn.enabled = NO;
204 | [UIView setAnimationsEnabled:NO];
205 | [_loadBtn setTitle:@"正在加载..." forState:UIControlStateNormal];
206 | [_loadBtn layoutIfNeeded];
207 | [UIView setAnimationsEnabled:YES];
208 | [_activityView startAnimating];
209 |
210 | [UIView beginAnimations:nil context:nil];
211 | [UIView setAnimationDuration:0.25f];
212 | _baseView.contentInset = _originalInsets;
213 | [UIView commitAnimations];
214 |
215 | // 获取更多数据时回调
216 | self.doLoadMoreCallBack?self.doLoadMoreCallBack():nil;
217 |
218 | }
219 | else if (state == SPLoadMoreStateNormal)
220 | {
221 | _refreshingFlag = NO;
222 |
223 | _loadBtn.enabled = YES;
224 | [UIView setAnimationsEnabled:NO];
225 | [_loadBtn setTitle:_moreString forState:UIControlStateNormal];
226 | [_loadBtn layoutIfNeeded];
227 | [UIView setAnimationsEnabled:YES];
228 | [_activityView stopAnimating];
229 |
230 | }
231 | else if (state == SPLoadMoreStateHasNoMore)
232 | {
233 | _refreshingFlag = YES;
234 |
235 | _loadBtn.enabled = NO;
236 | [UIView setAnimationsEnabled:NO];
237 | [_loadBtn setTitle:_noMoreString?_noMoreString:@"-End-" forState:UIControlStateNormal];
238 | [_loadBtn layoutIfNeeded];
239 | [UIView setAnimationsEnabled:YES];
240 | [_activityView stopAnimating];
241 |
242 | [UIView beginAnimations:nil context:nil];
243 | [UIView setAnimationDuration:0.25f];
244 | _baseView.contentInset = _originalInsets;
245 | [UIView commitAnimations];
246 |
247 | }
248 |
249 | }
250 |
251 | - (void)dealloc{
252 | [self.baseView removeObserver:self forKeyPath:k_contentSize];
253 | }
254 |
255 | @end
256 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPRefreshView/SPRefreshControl.h:
--------------------------------------------------------------------------------
1 | //
2 | // SPRefreshControl.h
3 | // SPLoadingSystem
4 | //
5 | // Created by Tree on 2017/4/18.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | typedef NS_ENUM(NSInteger,SPRefreshState) {
12 |
13 | SPRefreshStatePulling = 1,
14 | SPRefreshStateNormal,
15 | SPRefreshStateRefreshing,
16 | SPRefreshStateNonAnimateRefreshing
17 |
18 | };
19 |
20 |
21 |
22 | @interface SPRefreshControl : UIControl
23 |
24 | // current state
25 | @property (nonatomic, assign) SPRefreshState refreshState;
26 |
27 | // call this block to change the view's loading property
28 | @property (nonatomic, copy) void(^refreshControlisRefreshing)(BOOL isRefreshing);
29 |
30 | @end
31 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPRefreshView/SPRefreshControl.m:
--------------------------------------------------------------------------------
1 | //
2 | // SPRefreshControl.m
3 | // SPLoadingSystem
4 | //
5 | // Created by Tree on 2017/4/18.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import "SPRefreshControl.h"
10 | #import "SPEasyLoadingHeader.h"
11 |
12 |
13 | @interface SPRefreshControl(){
14 |
15 | BOOL _refreshingFlag;
16 | BOOL _isCollectionViewFlag;
17 | BOOL _autoAdjustContentInset;
18 |
19 | CGPoint _originalOffsets;
20 | CGFloat _conditionValue;
21 | UIEdgeInsets _originalInsets;
22 | CGRect _originalRefreshFrame;
23 |
24 | }
25 |
26 | @property (nonatomic, weak) UIScrollView *baseView;
27 | @property (nonatomic, strong) UILabel *refreshTipLabel;
28 | @property (nonatomic, strong) UIImageView *refreshArrowImg;
29 | @property (nonatomic, strong) UIActivityIndicatorView *refreshIndicator;
30 |
31 | @end
32 |
33 | @implementation SPRefreshControl
34 |
35 | - (instancetype)initWithFrame:(CGRect)frame{
36 |
37 | if (self = [super initWithFrame:frame]) {
38 | [self initialize];
39 | }
40 | return self;
41 | }
42 |
43 | - (void)willMoveToSuperview:(UIView *)newSuperview{
44 | [super willMoveToSuperview:newSuperview];
45 |
46 | if (newSuperview && ![newSuperview isKindOfClass:[UIScrollView class]]) return;
47 |
48 | [self.superview removeObserver:self forKeyPath:k_contentOffset];
49 |
50 | if (newSuperview) {
51 | self.baseView = (UIScrollView *)newSuperview;
52 | self.baseView.alwaysBounceVertical = YES;
53 | _originalRefreshFrame = self.frame;
54 | }
55 |
56 | if ([newSuperview isKindOfClass:[UICollectionView class]]) {
57 | _isCollectionViewFlag = YES;
58 | }
59 |
60 | }
61 |
62 | - (void)layoutSubviews{
63 | if (_isCollectionViewFlag) {
64 | self.frame = CGRectOffset(_originalRefreshFrame,
65 | -_baseView.contentInset.left,
66 | -_baseView.contentInset.top);
67 | }
68 |
69 | if (_refreshState == SPRefreshStateNormal ||
70 | _refreshState == SPRefreshStateNonAnimateRefreshing) {
71 | _originalInsets = _baseView.contentInset;
72 | _originalOffsets = _baseView.contentOffset;
73 |
74 | }
75 |
76 | [super layoutSubviews];
77 | }
78 |
79 | #pragma mark - kvo
80 | - (void)setBaseView:(UITableView *)baseView{
81 | _baseView = baseView;
82 | [baseView addObserver:self forKeyPath:k_contentOffset options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
83 |
84 | }
85 |
86 | - (UIViewController *)getCurrentViewController:(UIView *) currentView{
87 |
88 | if ([currentView superview]) {
89 | for (UIView* next = [currentView superview]; next; next = next.superview){
90 | UIResponder *nextResponder = [next nextResponder];
91 | if ([nextResponder isKindOfClass:[UIViewController class]])
92 | {
93 | return (UIViewController *)nextResponder;
94 | }
95 | }
96 | }else{
97 | return (UIViewController *)[currentView nextResponder];
98 | }
99 | return nil;
100 | }
101 |
102 | - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
103 |
104 | if ([keyPath isEqualToString:k_contentOffset]) {
105 |
106 | // id newChange = [change objectForKey:NSKeyValueChangeNewKey];// object for key / value for key
107 | // NSString *newChangeStr = [NSString stringWithFormat:@"%@",newChange];
108 | // CGPoint newPoint = CGPointFromString(newChangeStr);
109 | // NSLog(@" contentoffset_Y ---> %f",newPoint.y);
110 | [self changeAppearanceWithBaseView:_baseView];
111 |
112 | }
113 |
114 | }
115 |
116 | - (void)changeAppearanceWithBaseView:(UIScrollView *)baseView{
117 |
118 | // CGFloat contentInsetTop = baseView.contentInset.top;
119 | CGFloat contentOffsety = baseView.contentOffset.y;
120 |
121 | BOOL isBaseIniPhoneX = NO;
122 | if (baseView.frame.size.height == 812) {// iPhone X
123 | isBaseIniPhoneX = YES;
124 | }
125 |
126 | CGFloat conditionValue = - refreshControlHeight + _originalOffsets.y;
127 | _conditionValue = conditionValue;
128 |
129 | if (baseView.dragging)
130 | {
131 | _refreshArrowImg.hidden = NO;
132 | _refreshIndicator.hidden = YES;
133 | _refreshTipLabel.hidden = NO;
134 |
135 | if (contentOffsety <= conditionValue && _refreshState == SPRefreshStateNormal)
136 | {
137 | self.refreshState = SPRefreshStatePulling;
138 | NSLog(@"Pulling");
139 | NSLog(@"\ncontentOffsetY:%f\nconditionValue:%f",contentOffsety,conditionValue);
140 | }
141 | else if (contentOffsety > conditionValue && _refreshState == SPRefreshStatePulling)
142 | {
143 | self.refreshState = SPRefreshStateNormal;
144 | NSLog(@"Normal");
145 | NSLog(@"\ncontentOffsetY:%f\nconditionValue:%f",contentOffsety,conditionValue);
146 | }
147 |
148 | }
149 | else
150 | {
151 | if (_refreshState == SPRefreshStatePulling) {// 不拖拽则进入刷新状态
152 | self.refreshState = SPRefreshStateRefreshing;
153 | NSLog(@"Refreshing");
154 | NSLog(@"\ncontentOffsetY:%f\nconditionValue:%f",contentOffsety,conditionValue);
155 | }else{
156 | if (contentOffsety >= _originalOffsets.y) {
157 | _refreshArrowImg.hidden = YES;
158 | _refreshIndicator.hidden = YES;
159 | _refreshTipLabel.hidden = YES;
160 | }
161 | NSLog(@"Recover");
162 | NSLog(@"\ncontentOffsetY:%f\nconditionValue:%f",contentOffsety,conditionValue);
163 | }
164 | // NSLog(@"contentOffset %f",contentOffsety);
165 | }
166 | // NSLog(@"----> Intime Change <----");
167 | // NSLog(@"\ncontentOffsetY:%f\nconditionValue:%f",contentOffsety,conditionValue);
168 | }
169 |
170 |
171 |
172 | #pragma mark - initialize ui
173 | - (void)initialize{
174 |
175 | self.refreshIndicator.center = CGPointMake(self.bounds.size.width/2.0 - 30, self.bounds.size.height/2.0);
176 | self.refreshTipLabel.center = CGPointMake(self.bounds.size.width/2.0 + 10, self.bounds.size.height/2.0);
177 | self.refreshArrowImg.center = self.refreshIndicator.center;
178 |
179 |
180 | [self addSubview:_refreshArrowImg];
181 | [self addSubview:_refreshIndicator];
182 | [self addSubview:_refreshTipLabel];
183 |
184 | self.refreshState = SPRefreshStateNormal;
185 |
186 | }
187 |
188 |
189 | #pragma mark - set
190 | - (void)setRefreshState:(SPRefreshState)refreshState{
191 |
192 | BOOL isRefreshing = refreshState == SPRefreshStateRefreshing;
193 | self.refreshControlisRefreshing?self.refreshControlisRefreshing(isRefreshing):nil;
194 |
195 | switch (refreshState) {
196 | case SPRefreshStatePulling:
197 | {
198 | _refreshingFlag = NO;
199 | _refreshTipLabel.text = @"松开刷新";
200 | _refreshArrowImg.hidden = NO;
201 | _refreshIndicator.hidden = YES;
202 | _refreshTipLabel.hidden = NO;
203 | [UIView animateWithDuration:0.25f animations:^{
204 | _refreshArrowImg.transform = CGAffineTransformMakeRotation(M_PI);
205 | }];
206 | }
207 | break;
208 | case SPRefreshStateNormal:
209 | {
210 | _refreshingFlag = NO;
211 |
212 | if (_refreshState == SPRefreshStateRefreshing ||
213 | _refreshState == SPRefreshStateNonAnimateRefreshing)
214 | {
215 | [UIView animateWithDuration:0.25f animations:^{
216 |
217 | self.baseView.contentInset = _originalInsets;
218 |
219 | } completion:^(BOOL finished) {
220 |
221 | _refreshArrowImg.hidden = YES;
222 | _refreshIndicator.hidden = YES;
223 | _refreshTipLabel.hidden = YES;
224 | _refreshTipLabel.text = @"下拉刷新";
225 | _refreshArrowImg.transform = CGAffineTransformIdentity;
226 | [_refreshIndicator stopAnimating];
227 |
228 | }];
229 | }
230 | else// 初始化时 全部隐藏
231 | {
232 | _refreshArrowImg.hidden = YES;
233 | _refreshIndicator.hidden = YES;
234 | _refreshTipLabel.hidden = YES;
235 | _refreshTipLabel.text = @"下拉刷新";
236 | [_refreshIndicator stopAnimating];
237 |
238 | [UIView animateWithDuration:0.25f animations:^{
239 | _refreshArrowImg.transform = CGAffineTransformIdentity;
240 | }];
241 | }
242 |
243 | }
244 | break;
245 | case SPRefreshStateRefreshing:
246 | {
247 | _refreshArrowImg.hidden = YES;
248 | _refreshIndicator.hidden = NO;
249 | _refreshTipLabel.hidden = NO;
250 | _refreshTipLabel.text = @"正在刷新";
251 | [_refreshIndicator startAnimating];
252 |
253 |
254 | [UIView animateWithDuration:0.25f animations:^{
255 | self.baseView.contentInset = UIEdgeInsetsMake(_isCollectionViewFlag?refreshControlHeight + _originalInsets.top:refreshControlHeight, _originalInsets.left, _originalInsets.bottom, _originalInsets.right);
256 | [self.baseView setContentOffset:CGPointMake(_originalOffsets.x, _originalOffsets.y - refreshControlHeight) animated:NO];
257 | }];
258 | if (!_refreshingFlag) {
259 | _refreshingFlag = YES;
260 | [self sendActionsForControlEvents:UIControlEventValueChanged];
261 | }
262 |
263 | }
264 | break;
265 | case SPRefreshStateNonAnimateRefreshing:// 不做任何处理
266 | {
267 | [self sendActionsForControlEvents:UIControlEventValueChanged];
268 | }
269 | break;
270 | }
271 |
272 | _refreshState = refreshState;
273 |
274 | }
275 |
276 |
277 | #pragma mark - get
278 | - (UILabel *)refreshTipLabel{
279 |
280 | if (!_refreshTipLabel) {
281 | _refreshTipLabel = [[UILabel alloc] init];
282 | _refreshTipLabel.textColor = [UIColor lightGrayColor];
283 | _refreshTipLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightLight];
284 | _refreshTipLabel.text = @"下拉刷新";
285 | [_refreshTipLabel sizeToFit];
286 | }
287 | return _refreshTipLabel;
288 | }
289 |
290 | - (UIImageView *)refreshArrowImg{
291 |
292 | if (!_refreshArrowImg) {
293 | _refreshArrowImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sp_arrow"]];
294 | [_refreshArrowImg sizeToFit];
295 | }
296 | return _refreshArrowImg;
297 | }
298 |
299 | - (UIActivityIndicatorView *)refreshIndicator{
300 |
301 | if (!_refreshIndicator) {
302 | _refreshIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
303 | }
304 | return _refreshIndicator;
305 | }
306 |
307 | - (void)removeFromSuperview{
308 | [super removeFromSuperview];
309 | [self.baseView removeObserver:self forKeyPath:k_contentOffset];
310 | }
311 |
312 |
313 | @end
314 |
315 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPSupportFiles/sp_arrow@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Tr2e/SPWaterFlowLayout/64f1ded92f26ea32297361ff80a2bdcc849f7992/WaterFlowLayout/SPEasyLoading/SPSupportFiles/sp_arrow@2x.png
--------------------------------------------------------------------------------
/WaterFlowLayout/SPEasyLoading/SPSupportFiles/sp_blank@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Tr2e/SPWaterFlowLayout/64f1ded92f26ea32297361ff80a2bdcc849f7992/WaterFlowLayout/SPEasyLoading/SPSupportFiles/sp_blank@2x.png
--------------------------------------------------------------------------------
/WaterFlowLayout/SPProductModel/SPProductModel.h:
--------------------------------------------------------------------------------
1 | //
2 | // SPProductModel.h
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/19.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface SPProductModel : NSObject
12 | @property (nonatomic, assign) NSInteger h; // 商品图片高
13 | @property (nonatomic, assign) NSInteger w; // 商品图片宽
14 | @property (nonatomic, copy) NSString *img; // 商品图片地址
15 | @property (nonatomic, copy) NSString *price; // 商品价格
16 |
17 | + (instancetype)productWithDict:(NSDictionary *)dict; // 字典转模型
18 | + (NSArray *)productWithIndex:(NSInteger)index; // 根据索引返回商品数组
19 |
20 | @end
21 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPProductModel/SPProductModel.m:
--------------------------------------------------------------------------------
1 | //
2 | // SPProductModel.m
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/19.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import "SPProductModel.h"
10 |
11 | @implementation SPProductModel
12 | + (instancetype)productWithDict:(NSDictionary *)dict {
13 | id good = [[self alloc] init];
14 | [good setValuesForKeysWithDictionary:dict];
15 | return good;
16 | }
17 |
18 | + (NSArray *)productWithIndex:(NSInteger)index {
19 |
20 | NSString *fileName = [NSString stringWithFormat:@"%ld.plist", index % 3 + 1];
21 | NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
22 | NSArray *goodsArray = [NSArray arrayWithContentsOfFile:path];
23 | NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:goodsArray.count];
24 |
25 | [goodsArray enumerateObjectsUsingBlock: ^(NSDictionary *dict, NSUInteger idx, BOOL *stop) {
26 | [tmpArray addObject:[self productWithDict:dict]];
27 | }];
28 | return tmpArray.copy;
29 | }
30 | @end
31 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPSelfSizeCell.h:
--------------------------------------------------------------------------------
1 | //
2 | // SPSelfSizeCell.h
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/18.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import
10 | #import "UICollectionViewCell+FeedData.h"
11 |
12 | @interface SPSelfSizeCell : UICollectionViewCell
13 |
14 | @end
15 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPSelfSizeCell.m:
--------------------------------------------------------------------------------
1 | //
2 | // SPSelfSizeCell.m
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/18.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import "SPSelfSizeCell.h"
10 | #import "UIImageView+WebCache.h"
11 | #import "SPProductModel.h"
12 |
13 | @interface SPSelfSizeCell()
14 | @property (weak, nonatomic) IBOutlet UILabel *numberLabel;
15 | @property (weak, nonatomic) IBOutlet UIImageView *productImg;
16 | @property (weak, nonatomic) IBOutlet UILabel *detailLabel;
17 | @end
18 |
19 | @implementation SPSelfSizeCell
20 |
21 | - (void)awakeFromNib{
22 | [super awakeFromNib];
23 | self.layer.borderColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.6].CGColor;
24 | self.layer.borderWidth = 1;
25 | }
26 |
27 | - (void)setFeedData:(SPProductModel *)feedData{
28 | self.detailLabel.text = feedData.img;
29 | [self.productImg sd_setImageWithURL:[NSURL URLWithString:feedData.img]];
30 | }
31 |
32 | - (void)setSubfeedData:(NSNumber *)subfeedData{
33 | self.numberLabel.text = [NSString stringWithFormat:@"%@",subfeedData];
34 | }
35 |
36 | @end
37 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPWaterFlowLayout.h:
--------------------------------------------------------------------------------
1 | //
2 | // SPWaterFlowLayout.h
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/6.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface SPWaterFlowLayout : UICollectionViewLayout
12 |
13 | /** 列数 */
14 | @property (nonatomic, assign) NSInteger columnNumber;
15 | /** 列间距 */
16 | @property (nonatomic, assign) NSInteger interitemSpacing;
17 | /** 行间距 */
18 | @property (nonatomic, assign) NSInteger lineSpacing;
19 | /** 页面大小 */
20 | @property (nonatomic, assign) NSInteger pageSize;
21 | /** cell的reuseIdentifier */
22 | @property (nonatomic, copy) NSString *reuseIdentifier;
23 | /** 数据源 */
24 | @property (nonatomic, strong) NSArray *datas;
25 |
26 | @end
27 |
--------------------------------------------------------------------------------
/WaterFlowLayout/SPWaterFlowLayout.m:
--------------------------------------------------------------------------------
1 | //
2 | // SPWaterFlowLayout.m
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/6.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import "SPWaterFlowLayout.h"
10 | #import "UICollectionViewCell+FeedData.h"
11 |
12 | struct SPColumnInfo
13 | {
14 | NSInteger columnNumber;
15 | CGFloat columnHeight;
16 | };
17 |
18 |
19 | @interface SPWaterFlowLayout()
20 | @property (nonatomic, strong) NSMutableArray *layoutAttributesArray;
21 | @property (nonatomic, strong) NSMutableArray *columnHeightArray;// 每列的总高度
22 | @property (nonatomic, strong) NSMutableArray *itemSizeArray;
23 | @property (nonatomic, assign) CGFloat itemWidth;
24 | @property (nonatomic, assign) UIEdgeInsets viewInset;
25 |
26 | @property (nonatomic, strong) UICollectionViewCell *templateCell;
27 |
28 | @end
29 |
30 | @implementation SPWaterFlowLayout
31 |
32 | - (void)prepareLayout{
33 | [super prepareLayout];
34 | NSInteger column = self.columnNumber;
35 | CGFloat contentWidth = self.collectionView.bounds.size.width - self.collectionView.contentInset.left - self.collectionView.contentInset.right;
36 | CGFloat itemSpace = self.interitemSpacing;
37 | CGFloat itemWidth = ( contentWidth - (column - 1) * itemSpace ) / column;
38 | self.itemWidth = itemWidth;
39 | self.viewInset = self.collectionView.contentInset;
40 | [self calculateAttributesWithItemWidth:itemWidth];
41 | }
42 |
43 | #pragma mark - Calculation Part
44 | - (void)calculateAttributesWithItemWidth:(CGFloat)itemWidth{
45 | BOOL isRefresh = self.datas.count <= self.pageSize;
46 | if (isRefresh) {
47 | [self refreshLayoutCache];
48 | }
49 | NSInteger cacheCount = self.itemSizeArray.count;
50 | for (NSInteger i = cacheCount; i < self.datas.count; i ++) {
51 | CGSize itemSize = [self calculateItemSizeWithIndex:i];
52 | UICollectionViewLayoutAttributes *layoutAttributes = [self createLayoutAttributesWithItemSize:itemSize index:i];
53 | [self.itemSizeArray addObject:[NSValue valueWithCGSize:itemSize]];
54 | [self.layoutAttributesArray addObject:layoutAttributes];
55 | }
56 | }
57 |
58 | - (UICollectionViewLayoutAttributes *)createLayoutAttributesWithItemSize:(CGSize)itemSize index:(NSInteger)index{
59 | UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
60 | struct SPColumnInfo shortestInfo = [self shortestColumn:self.columnHeightArray];
61 | // x
62 | CGFloat itemX = (self.itemWidth + self.interitemSpacing) * shortestInfo.columnNumber;
63 | // y
64 | CGFloat itemY = self.columnHeightArray[shortestInfo.columnNumber].floatValue + self.lineSpacing;
65 | // size
66 | layoutAttributes.frame = (CGRect){CGPointMake(itemX, itemY),itemSize};
67 | self.columnHeightArray[shortestInfo.columnNumber] = @(CGRectGetMaxY(layoutAttributes.frame));
68 | return layoutAttributes;
69 | }
70 |
71 | - (CGSize)calculateItemSizeWithIndex:(NSInteger)index{
72 | NSAssert(index < self.datas.count, @"index is incorrect");
73 | UICollectionViewCell *tempCell = [self templateCellWithReuseIdentifier:self.reuseIdentifier withIndex:index];
74 | tempCell.feedData = self.datas[index];
75 | CGFloat cellHeight = [self systemCalculateHeightForTemplateCell:tempCell];
76 | return CGSizeMake(self.itemWidth, cellHeight);
77 | }
78 |
79 | - (CGFloat)systemCalculateHeightForTemplateCell:(UICollectionViewCell *)cell{
80 | CGFloat calculateHeight = 0;
81 |
82 | NSLayoutConstraint *widthForceConstant = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:self.itemWidth];
83 |
84 | static BOOL isSystemVersionEqualOrGreaterThen10_2 = NO;
85 | static dispatch_once_t onceToken;
86 | dispatch_once(&onceToken, ^{
87 | isSystemVersionEqualOrGreaterThen10_2 = [UIDevice.currentDevice.systemVersion compare:@"10.2" options:NSNumericSearch] != NSOrderedAscending;
88 | });
89 |
90 | NSArray *edgeConstraints;
91 | if (isSystemVersionEqualOrGreaterThen10_2) {
92 | // To avoid conflicts, make width constraint softer than required (1000)
93 | widthForceConstant.priority = UILayoutPriorityRequired - 1;
94 |
95 | // Build edge constraints
96 | NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
97 | NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
98 | NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
99 | NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
100 | edgeConstraints = @[leftConstraint, rightConstraint, topConstraint, bottomConstraint];
101 | [cell addConstraints:edgeConstraints];
102 | }
103 |
104 | // system calculate
105 | [cell.contentView addConstraint:widthForceConstant];
106 | calculateHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
107 | // clear constraint
108 | [cell.contentView removeConstraint:widthForceConstant];
109 | if (isSystemVersionEqualOrGreaterThen10_2) {
110 | [cell removeConstraints:edgeConstraints];
111 | }
112 | return calculateHeight;
113 | }
114 |
115 | - (UICollectionViewCell *)templateCellWithReuseIdentifier:(NSString *)reuseIdentifier withIndex:(NSInteger)index{
116 | if (!self.templateCell) {
117 | UICollectionViewCell *templateCell = [[NSBundle mainBundle] loadNibNamed:@"TestView" owner:nil options:nil].lastObject;
118 | self.templateCell = templateCell;
119 | }
120 | return self.templateCell;
121 | }
122 |
123 | - (void)refreshLayoutCache{
124 | [self.layoutAttributesArray removeAllObjects];
125 | [self.columnHeightArray removeAllObjects];
126 | [self.itemSizeArray removeAllObjects];
127 | for (NSInteger index = 0; index < self.columnNumber; index ++) {
128 | [self.columnHeightArray addObject:@(self.viewInset.top)];
129 | }
130 | }
131 |
132 | - (struct SPColumnInfo)highestColumn:(NSArray *)columnHeight{
133 | CGFloat max = 0;
134 | NSInteger column = 0;
135 | for (int i = 0; i < self.columnNumber; i++) {
136 | if (columnHeight[i].floatValue > max) {
137 | max = columnHeight[i].floatValue;
138 | column = i;
139 | }
140 | }
141 | struct SPColumnInfo info;
142 | info.columnNumber = column;
143 | info.columnHeight = max;
144 | return info;
145 | }
146 |
147 | - (struct SPColumnInfo)shortestColumn:(NSArray *)columnHeight{
148 | CGFloat min = CGFLOAT_MAX;
149 | NSInteger column = 0;
150 | for (int i = 0; i < self.columnNumber; i++) {
151 | if (columnHeight[i].floatValue < min) {
152 | min = columnHeight[i].floatValue;
153 | column = i;
154 | }
155 | }
156 | NSLog(@"shortest column:%ld shortest height:%f",(long)column,min);
157 | struct SPColumnInfo info;
158 | info.columnNumber = column;
159 | info.columnHeight = min;
160 | return info;
161 | }
162 |
163 | #pragma mark - Override
164 | - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
165 | return self.layoutAttributesArray;
166 | }
167 |
168 | - (CGSize)collectionViewContentSize{
169 | struct SPColumnInfo maxInfo = [self highestColumn:self.columnHeightArray];
170 | CGFloat height = maxInfo.columnHeight + self.viewInset.bottom + self.lineSpacing;
171 | CGFloat width = self.collectionView.bounds.size.width - self.viewInset.left - self.viewInset.right;
172 | return CGSizeMake( width, height);
173 | }
174 |
175 | - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
176 | return self.layoutAttributesArray[indexPath.item];
177 | }
178 |
179 | #pragma mark - Basic init
180 | - (NSMutableArray *)layoutAttributesArray{
181 | if (!_layoutAttributesArray) {
182 | _layoutAttributesArray = [NSMutableArray array];
183 | }
184 | return _layoutAttributesArray;
185 | }
186 |
187 | - (NSMutableArray *)columnHeightArray{
188 | if (!_columnHeightArray) {
189 | _columnHeightArray = [NSMutableArray array];
190 | }
191 | return _columnHeightArray;
192 | }
193 |
194 | - (NSMutableArray *)itemSizeArray{
195 | if (!_itemSizeArray) {
196 | _itemSizeArray = [NSMutableArray array];
197 | }
198 | return _itemSizeArray;
199 | }
200 |
201 | @end
202 |
--------------------------------------------------------------------------------
/WaterFlowLayout/TestView.xib:
--------------------------------------------------------------------------------
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 |
34 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
--------------------------------------------------------------------------------
/WaterFlowLayout/UICollectionViewCell+FeedData.h:
--------------------------------------------------------------------------------
1 | //
2 | // UICollectionViewCell+FeedData.h
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/18.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface UICollectionViewCell (FeedData)
12 | @property (nonatomic, strong) id feedData;
13 | @property (nonatomic, strong) id subfeedData;
14 | @end
15 |
--------------------------------------------------------------------------------
/WaterFlowLayout/UICollectionViewCell+FeedData.m:
--------------------------------------------------------------------------------
1 | //
2 | // UICollectionViewCell+FeedData.m
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/18.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import "UICollectionViewCell+FeedData.h"
10 | #import
11 |
12 | static NSString *AssociateKeyFeedData = @"AssociateKeyFeedData";
13 | static NSString *AssociateKeySubFeedData = @"AssociateKeySubFeedData";
14 | @implementation UICollectionViewCell (FeedData)
15 | @dynamic feedData;
16 | @dynamic subfeedData;
17 |
18 | - (void)setFeedData:(id)feedData{
19 | objc_setAssociatedObject(self, &AssociateKeyFeedData, feedData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
20 | }
21 |
22 | - (id)feedData{
23 | return objc_getAssociatedObject(self, &AssociateKeyFeedData);
24 | }
25 |
26 | - (void)setSubfeedData:(id)subfeedData{
27 | objc_setAssociatedObject(self, &AssociateKeySubFeedData, subfeedData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
28 | }
29 |
30 | - (id)subfeedData{
31 | return objc_getAssociatedObject(self, &AssociateKeySubFeedData);
32 | }
33 |
34 | @end
35 |
--------------------------------------------------------------------------------
/WaterFlowLayout/ViewController.h:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.h
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/6.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface ViewController : UIViewController
12 |
13 |
14 | @end
15 |
16 |
--------------------------------------------------------------------------------
/WaterFlowLayout/ViewController.m:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.m
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/6.
6 | // Copyright © 2017年 Tr2e. All rights reserved.
7 | //
8 |
9 | #import "ViewController.h"
10 | #import "UICollectionViewCell+FeedData.h"
11 | #import "SPProductModel.h"
12 | #import "YYFPSLabel.h"
13 | #import "SPEasyLoadingForCollectionView.h"
14 | #import "SPWaterFlowLayout.h"
15 |
16 | @interface ViewController ()
17 | @property (nonatomic, strong) NSArray *datas;
18 |
19 | @property (nonatomic, strong) YYFPSLabel *fpsLabel;
20 | @property (nonatomic, assign) NSInteger pageTag;
21 |
22 | @end
23 |
24 | @implementation ViewController
25 |
26 | - (void)viewDidLoad {
27 | [super viewDidLoad];
28 | self.view.backgroundColor = [UIColor whiteColor];
29 |
30 | self.pageTag = 0;
31 |
32 | SPWaterFlowLayout *flowlayout = [[SPWaterFlowLayout alloc] init];
33 | flowlayout.columnNumber = 2;
34 | flowlayout.interitemSpacing = 10;
35 | flowlayout.lineSpacing = 10;
36 | flowlayout.pageSize = 54;
37 | flowlayout.reuseIdentifier = @"Cell";
38 | UICollectionView *test = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowlayout];
39 | test.contentInset = UIEdgeInsetsMake(10, 10, 5, 10);
40 | [self.view addSubview:test];
41 | test.delegate = self;
42 | test.dataSource = self;
43 | [test registerNib:[UINib nibWithNibName:@"TestView" bundle:nil] forCellWithReuseIdentifier:@"Cell"];
44 | test.backgroundColor = [UIColor whiteColor];
45 |
46 | test.canRefresh = YES;
47 | test.canAutoLoadMore = YES;
48 | test.pageSize = 54;
49 |
50 | __weak typeof(test) wtest = test;
51 | test.refreshDataCallBack = ^{
52 | dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
53 | self.pageTag = 0;
54 | NSArray *datas = [SPProductModel productWithIndex:0];
55 | flowlayout.datas = datas;
56 | wtest.sp_datas = [datas mutableCopy];
57 | [wtest doneLoadDatas];
58 | [wtest reloadData];
59 | });
60 | };
61 | test.loadMoreDataCallBack = ^{
62 | self.pageTag ++;
63 | dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
64 | NSArray *datas = [SPProductModel productWithIndex:self.pageTag];
65 | NSArray *total = [flowlayout.datas arrayByAddingObjectsFromArray:datas];
66 | flowlayout.datas = total;
67 | wtest.sp_datas = [total mutableCopy];
68 | [wtest doneLoadDatas];
69 | [wtest reloadData];
70 | });
71 | };
72 |
73 |
74 | _fpsLabel = [YYFPSLabel new];
75 | _fpsLabel.frame = CGRectMake(20, 35, 50, 30);
76 | [_fpsLabel sizeToFit];
77 | [self.view addSubview:_fpsLabel];
78 |
79 | [test beginNonAnimateRefreshing];
80 |
81 | }
82 |
83 | - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
84 | return 1;
85 | }
86 |
87 | - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
88 | return collectionView.sp_datas.count;
89 | }
90 |
91 | - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
92 | UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
93 | cell.feedData = collectionView.sp_datas[indexPath.item];
94 | cell.subfeedData = @(indexPath.item);
95 | return cell;
96 | }
97 |
98 | - (void)didReceiveMemoryWarning {
99 | [super didReceiveMemoryWarning];
100 | // Dispose of any resources that can be recreated.
101 | }
102 |
103 |
104 | @end
105 |
--------------------------------------------------------------------------------
/WaterFlowLayout/YYFPSLabel/YYFPSLabel.h:
--------------------------------------------------------------------------------
1 | //
2 | // YYFPSLabel.h
3 | // YYKitExample
4 | //
5 | // Created by ibireme on 15/9/3.
6 | // Copyright (c) 2015 ibireme. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | /**
12 | Show Screen FPS...
13 |
14 | The maximum fps in OSX/iOS Simulator is 60.00.
15 | The maximum fps on iPhone is 59.97.
16 | The maxmium fps on iPad is 60.0.
17 | */
18 | @interface YYFPSLabel : UILabel
19 |
20 | @end
21 |
--------------------------------------------------------------------------------
/WaterFlowLayout/YYFPSLabel/YYFPSLabel.m:
--------------------------------------------------------------------------------
1 | //
2 | // YYFPSLabel.m
3 | // YYKitExample
4 | //
5 | // Created by ibireme on 15/9/3.
6 | // Copyright (c) 2015 ibireme. All rights reserved.
7 | //
8 |
9 | #import "YYFPSLabel.h"
10 | #import "YYWeakProxy.h"
11 |
12 | #define kSize CGSizeMake(55, 20)
13 |
14 | @implementation YYFPSLabel {
15 | CADisplayLink *_link;
16 | NSUInteger _count;
17 | NSTimeInterval _lastTime;
18 | UIFont *_font;
19 | UIFont *_subFont;
20 |
21 | NSTimeInterval _llll;
22 | }
23 |
24 | - (instancetype)initWithFrame:(CGRect)frame {
25 | if (frame.size.width == 0 && frame.size.height == 0) {
26 | frame.size = kSize;
27 | }
28 | self = [super initWithFrame:frame];
29 |
30 | self.layer.cornerRadius = 5;
31 | self.clipsToBounds = YES;
32 | self.textAlignment = NSTextAlignmentCenter;
33 | self.userInteractionEnabled = NO;
34 | self.backgroundColor = [UIColor colorWithWhite:0.000 alpha:0.700];
35 |
36 | _font = [UIFont fontWithName:@"Menlo" size:14];
37 | if (_font) {
38 | _subFont = [UIFont fontWithName:@"Menlo" size:4];
39 | } else {
40 | _font = [UIFont fontWithName:@"Courier" size:14];
41 | _subFont = [UIFont fontWithName:@"Courier" size:4];
42 | }
43 |
44 | // 如果直接用 self 或者 weakSelf,都不能解决循环引用问题
45 |
46 | // 将 timer 的 target 从 self ,变成了中间人 NSProxy
47 | // timer 调用 target 的 selector 时,会被 NSProxy 内部转调用 self 的 selector
48 | _link = [CADisplayLink displayLinkWithTarget:[YYWeakProxy proxyWithTarget:self] selector:@selector(tick:)];
49 | // __weak typeof(self) weakSelf = self;
50 | // _link = [CADisplayLink displayLinkWithTarget:weakSelf selector:@selector(tick:)];
51 | [_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
52 |
53 | return self;
54 | }
55 |
56 | - (void)dealloc {
57 | [_link invalidate];
58 | NSLog(@"timer release");
59 | }
60 |
61 | - (CGSize)sizeThatFits:(CGSize)size {
62 | return kSize;
63 | }
64 |
65 | - (void)tick:(CADisplayLink *)link {
66 | if (_lastTime == 0) {
67 | _lastTime = link.timestamp;
68 | return;
69 | }
70 |
71 | _count++;
72 | NSTimeInterval delta = link.timestamp - _lastTime;
73 | if (delta < 1) return;
74 | _lastTime = link.timestamp;
75 | float fps = _count / delta;
76 | _count = 0;
77 |
78 | CGFloat progress = fps / 60.0;
79 | UIColor *color = [UIColor colorWithHue:0.27 * (progress - 0.2) saturation:1 brightness:0.9 alpha:1];
80 |
81 | // NSString *text1 = [NSString stringWithFormat:@"%d FPS",(int)round(fps)];
82 | // NSLog(@"%@", text1);
83 |
84 |
85 | NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d FPS",(int)round(fps)]];
86 | [text addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, text.length - 3)];
87 | [text addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(text.length - 3, 3)];
88 | [text addAttribute:NSFontAttributeName value:_font range:NSMakeRange(0, text.length)];
89 | [text addAttribute:NSFontAttributeName value:_subFont range:NSMakeRange(text.length - 4, 1)];
90 | self.attributedText = text;
91 | }
92 |
93 | @end
94 |
--------------------------------------------------------------------------------
/WaterFlowLayout/YYFPSLabel/YYWeakProxy.h:
--------------------------------------------------------------------------------
1 | //
2 | // YYWeakProxy.h
3 | // YYKit
4 | //
5 | // Created by ibireme on 14/10/18.
6 | // Copyright (c) 2015 ibireme.
7 | //
8 | // This source code is licensed under the MIT-style license found in the
9 | // LICENSE file in the root directory of this source tree.
10 | //
11 |
12 | #import
13 |
14 | /**
15 | A proxy used to hold a weak object.
16 | It can be used to avoid retain cycles, such as the target in NSTimer or CADisplayLink.
17 |
18 | sample code:
19 |
20 | @implementation MyView {
21 | NSTimer *_timer;
22 | }
23 |
24 | - (void)initTimer {
25 | YYWeakProxy *proxy = [YYWeakProxy proxyWithTarget:self];
26 | _timer = [NSTimer timerWithTimeInterval:0.1 target:proxy selector:@selector(tick:) userInfo:nil repeats:YES];
27 | }
28 |
29 | - (void)tick:(NSTimer *)timer {...}
30 | @end
31 | */
32 | @interface YYWeakProxy : NSProxy
33 |
34 | /**
35 | The proxy target.
36 | */
37 | @property (nonatomic, weak, readonly) id target;
38 |
39 | /**
40 | Creates a new weak proxy for target.
41 |
42 | @param target Target object.
43 |
44 | @return A new proxy object.
45 | */
46 | - (instancetype)initWithTarget:(id)target;
47 |
48 | /**
49 | Creates a new weak proxy for target.
50 |
51 | @param target Target object.
52 |
53 | @return A new proxy object.
54 | */
55 | + (instancetype)proxyWithTarget:(id)target;
56 |
57 | @end
58 |
--------------------------------------------------------------------------------
/WaterFlowLayout/YYFPSLabel/YYWeakProxy.m:
--------------------------------------------------------------------------------
1 | //
2 | // YYWeakProxy.m
3 | // YYKit
4 | //
5 | // Created by ibireme on 14/10/18.
6 | // Copyright (c) 2015 ibireme.
7 | //
8 | // This source code is licensed under the MIT-style license found in the
9 | // LICENSE file in the root directory of this source tree.
10 | //
11 |
12 | #import "YYWeakProxy.h"
13 |
14 | /**
15 | 实现的原理: 使用 NSProxy 持有 NSTimer 的 target
16 | 不再用 NSTimer 直接持有 self,就不会导致 timer 对 self 的循环强引用了
17 | */
18 | @implementation YYWeakProxy
19 |
20 | - (instancetype)initWithTarget:(id)target {
21 | _target = target;
22 | return self;
23 | }
24 |
25 | //类方法
26 | + (instancetype)proxyWithTarget:(id)target {
27 | return [[YYWeakProxy alloc] initWithTarget:target];
28 | }
29 |
30 | #pragma mark - private
31 |
32 | - (id)forwardingTargetForSelector:(SEL)selector {
33 | return _target;
34 | }
35 |
36 | #pragma mark - over write
37 |
38 | //重写NSProxy如下两个方法,在处理消息转发时,将消息转发给真正的Target处理
39 | - (void)forwardInvocation:(NSInvocation *)invocation {
40 | void *null = NULL;
41 | [invocation setReturnValue:&null];
42 | }
43 |
44 | - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
45 | return [NSObject instanceMethodSignatureForSelector:@selector(init)];
46 | }
47 |
48 | - (BOOL)respondsToSelector:(SEL)aSelector {
49 | return [_target respondsToSelector:aSelector];
50 | }
51 |
52 | #pragma mark -
53 |
54 | - (BOOL)isEqual:(id)object {
55 | return [_target isEqual:object];
56 | }
57 |
58 | - (NSUInteger)hash {
59 | return [_target hash];
60 | }
61 |
62 | - (Class)superclass {
63 | return [_target superclass];
64 | }
65 |
66 | - (Class)class {
67 | return [_target class];
68 | }
69 |
70 | - (BOOL)isKindOfClass:(Class)aClass {
71 | return [_target isKindOfClass:aClass];
72 | }
73 |
74 | - (BOOL)isMemberOfClass:(Class)aClass {
75 | return [_target isMemberOfClass:aClass];
76 | }
77 |
78 | - (BOOL)conformsToProtocol:(Protocol *)aProtocol {
79 | return [_target conformsToProtocol:aProtocol];
80 | }
81 |
82 | - (BOOL)isProxy {
83 | return YES;
84 | }
85 |
86 | - (NSString *)description {
87 | return [_target description];
88 | }
89 |
90 | - (NSString *)debugDescription {
91 | return [_target debugDescription];
92 | }
93 |
94 | @end
95 |
--------------------------------------------------------------------------------
/WaterFlowLayout/main.m:
--------------------------------------------------------------------------------
1 | //
2 | // main.m
3 | // WaterFlowLayout
4 | //
5 | // Created by Tree on 2017/9/6.
6 | // Copyright © 2017年 Tr2e. 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 |
--------------------------------------------------------------------------------
/waterflow.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Tr2e/SPWaterFlowLayout/64f1ded92f26ea32297361ff80a2bdcc849f7992/waterflow.gif
--------------------------------------------------------------------------------