├── VVeboTableViewDemo
├── t_comments@2x.png
├── t_repost@2x.png
├── corner_circle@2x.png
├── VVeboTableView.h
├── ViewController.h
├── SDWebImage
│ ├── UIImage+MultiFormat.h
│ ├── SDWebImageOperation.h
│ ├── UIImage+GIF.h
│ ├── NSData+ImageContentType.h
│ ├── SDWebImageDecoder.h
│ ├── UIImage+WebP.h
│ ├── UIView+WebCacheOperation.h
│ ├── NSData+ImageContentType.m
│ ├── SDWebImageCompat.m
│ ├── SDWebImageCompat.h
│ ├── UIView+WebCacheOperation.m
│ ├── UIImage+WebP.m
│ ├── SDWebImageDownloaderOperation.h
│ ├── SDWebImageDecoder.m
│ ├── MKAnnotationView+WebCache.m
│ ├── UIImageView+HighlightedWebCache.m
│ ├── UIImage+MultiFormat.m
│ ├── SDWebImagePrefetcher.h
│ ├── UIImageView+HighlightedWebCache.h
│ ├── MKAnnotationView+WebCache.h
│ ├── UIImage+GIF.m
│ ├── SDWebImagePrefetcher.m
│ ├── UIImageView+WebCache.m
│ ├── SDWebImageDownloader.h
│ ├── UIButton+WebCache.m
│ ├── SDImageCache.h
│ ├── UIImageView+WebCache.h
│ ├── SDWebImageManager.h
│ ├── UIButton+WebCache.h
│ ├── SDWebImageDownloader.m
│ └── SDWebImageManager.m
├── AppDelegate.h
├── UIScreen+Additions.h
├── main.m
├── view
│ ├── VVeboLabel.h
│ ├── VVeboTableViewCell.h
│ └── VVeboTableViewCell.m
├── ViewController.m
├── Images.xcassets
│ └── AppIcon.appiconset
│ │ └── Contents.json
├── Info.plist
├── NSString+Additions.h
├── Base.lproj
│ ├── Main.storyboard
│ └── LaunchScreen.xib
├── AppDelegate.m
├── UIView+Additions.h
├── UIScreen+Additions.m
├── NSString+Additions.m
├── VVeboTableView.m
└── UIView+Additions.m
├── VVeboTableViewDemo.xcodeproj
└── project.xcworkspace
│ └── contents.xcworkspacedata
├── README.md
├── .gitignore
└── VVeboTableViewDemoTests
├── Info.plist
└── VVeboTableViewDemoTests.m
/VVeboTableViewDemo/t_comments@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/johnil/VVeboTableViewDemo/HEAD/VVeboTableViewDemo/t_comments@2x.png
--------------------------------------------------------------------------------
/VVeboTableViewDemo/t_repost@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/johnil/VVeboTableViewDemo/HEAD/VVeboTableViewDemo/t_repost@2x.png
--------------------------------------------------------------------------------
/VVeboTableViewDemo/corner_circle@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/johnil/VVeboTableViewDemo/HEAD/VVeboTableViewDemo/corner_circle@2x.png
--------------------------------------------------------------------------------
/VVeboTableViewDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/VVeboTableView.h:
--------------------------------------------------------------------------------
1 | //
2 | // VVeboTableView.h
3 | // VVeboTableViewDemo
4 | //
5 | // Created by Johnil on 15/5/25.
6 | // Copyright (c) 2015年 Johnil. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface VVeboTableView : UITableView
12 |
13 | @end
14 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/ViewController.h:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.h
3 | // VVeboTableViewDemo
4 | //
5 | // Created by Johnil on 15/5/25.
6 | // Copyright (c) 2015年 Johnil. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface ViewController : UIViewController
12 |
13 |
14 | @end
15 |
16 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/AppDelegate.h:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.h
3 | // VVeboTableViewDemo
4 | //
5 | // Created by Johnil on 15/5/25.
6 | // Copyright (c) 2015年 Johnil. 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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/UIScreen+Additions.h:
--------------------------------------------------------------------------------
1 | //
2 | // UIScreen+Additions.h
3 | // Additions
4 | //
5 | // Created by Johnil on 13-6-15.
6 | // Copyright (c) 2013年 Johnil. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface UIScreen (Additions)
12 |
13 | + (float)screenWidth;
14 | + (float)screenHeight;
15 | + (BOOL)isRetina;
16 | + (float)scale;
17 |
18 | @end
19 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/main.m:
--------------------------------------------------------------------------------
1 | //
2 | // main.m
3 | // VVeboTableViewDemo
4 | //
5 | // Created by Johnil on 15/5/25.
6 | // Copyright (c) 2015年 Johnil. 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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # VVeboTableViewDemo
2 |
3 | 此项目由VVebo剥离,希望你能通过这个demo看到我是如何进行TableView流畅度优化的。
4 |
5 | 主要思路如下:
6 |
7 | 1.异步渲染内容到图片。
8 |
9 | 2.按照滑动速度按需加载内容。
10 |
11 | 3.重写处理网络图片加载。
12 |
13 | 实际上做完前两点就可以很流畅了。我把内容都异步渲染到了一张图上,尽可能减少Cell层级。
14 |
15 | 项目中我用的是SDWebImageManager。在我变态级要求下,网络图片加载的线程还是会引起丝毫卡顿的。在VVebo中我将网络图片加载重写了。此demo中我并没有将重写图片加载的内容剥离,单单这样已经可以很流畅了。
16 |
17 | 新浪微博:[@Johnil](http://weibo.com/u/3732851864)
18 |
19 | 如果你有任何疑问,欢迎随时到新浪微博来交流。
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Xcode
2 | #
3 | build/
4 | *.pbxuser
5 | !default.pbxuser
6 | *.mode1v3
7 | !default.mode1v3
8 | *.mode2v3
9 | !default.mode2v3
10 | *.perspectivev3
11 | !default.perspectivev3
12 | xcuserdata
13 | *.xccheckout
14 | *.moved-aside
15 | DerivedData
16 | *.hmap
17 | *.ipa
18 | *.xcuserstate
19 |
20 | # CocoaPods
21 | #
22 | # We recommend against adding the Pods directory to your .gitignore. However
23 | # you should judge for yourself, the pros and cons are mentioned at:
24 | # http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
25 | #
26 | #Pods/
27 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/view/VVeboLabel.h:
--------------------------------------------------------------------------------
1 | //
2 | // VVeboLabel.h
3 | // VVeboTableViewDemo
4 | //
5 | // Created by Johnil on 15/5/25.
6 | // Copyright (c) 2015年 Johnil. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface VVeboLabel : UIView
12 |
13 | @property (nonatomic, strong) NSString *text;
14 | @property (nonatomic, strong) UIColor *textColor;
15 | @property (nonatomic, strong) UIFont *font;
16 | @property (nonatomic) NSInteger lineSpace;
17 | @property (nonatomic) NSTextAlignment textAlignment;
18 |
19 | - (void)debugDraw;
20 | - (void)clear;
21 | - (BOOL)touchPoint:(CGPoint)point;
22 |
23 | @end
24 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/SDWebImage/UIImage+WebP.h:
--------------------------------------------------------------------------------
1 | //
2 | // UIImage+WebP.h
3 | // SDWebImage
4 | //
5 | // Created by Olivier Poitrey on 07/06/13.
6 | // Copyright (c) 2013 Dailymotion. All rights reserved.
7 | //
8 |
9 | #ifdef SD_WEBP
10 |
11 | #import
12 |
13 | // Fix for issue #416 Undefined symbols for architecture armv7 since WebP introduction when deploying to device
14 | void WebPInitPremultiplyNEON(void);
15 |
16 | void WebPInitUpsamplersNEON(void);
17 |
18 | void VP8DspInitNEON(void);
19 |
20 | @interface UIImage (WebP)
21 |
22 | + (UIImage *)sd_imageWithWebPData:(NSData *)data;
23 |
24 | @end
25 |
26 | #endif
27 |
--------------------------------------------------------------------------------
/VVeboTableViewDemoTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | com.johnil.$(PRODUCT_NAME:rfc1034identifier)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/view/VVeboTableViewCell.h:
--------------------------------------------------------------------------------
1 | //
2 | // VVeboTableViewCell.h
3 | // VVeboTableViewDemo
4 | //
5 | // Created by Johnil on 15/5/25.
6 | // Copyright (c) 2015年 Johnil. All rights reserved.
7 | //
8 |
9 | #import
10 | #define SIZE_GAP_LEFT 15
11 | #define SIZE_GAP_TOP 13
12 | #define SIZE_AVATAR 40
13 | #define SIZE_GAP_BIG 10
14 | #define SIZE_GAP_IMG 5
15 | #define SIZE_GAP_SMALL 5
16 | #define SIZE_IMAGE 80
17 | #define SIZE_FONT 17
18 | #define SIZE_FONT_NAME (SIZE_FONT-3)
19 | #define SIZE_FONT_SUBTITLE (SIZE_FONT-8)
20 | #define FontWithSize(s) [UIFont fontWithName:@"HelveticaNeue-Light" size:s]
21 | #define SIZE_FONT_CONTENT 17
22 | #define SIZE_FONT_SUBCONTENT (SIZE_FONT_CONTENT-1)
23 |
24 | @interface VVeboTableViewCell : UITableViewCell
25 |
26 | @property (nonatomic, weak) NSDictionary *data;
27 | - (void)draw;
28 | - (void)clear;
29 | - (void)releaseMemory;
30 |
31 | @end
32 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/ViewController.m:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.m
3 | // VVeboTableViewDemo
4 | //
5 | // Created by Johnil on 15/5/25.
6 | // Copyright (c) 2015年 Johnil. All rights reserved.
7 | //
8 |
9 | #import "ViewController.h"
10 | #import "VVeboTableView.h"
11 | @interface ViewController ()
12 |
13 | @end
14 |
15 | @implementation ViewController {
16 | VVeboTableView *tableView;
17 | }
18 |
19 | - (void)viewDidLoad {
20 | [super viewDidLoad];
21 | tableView = [[VVeboTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
22 | tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
23 | tableView.scrollIndicatorInsets = tableView.contentInset;
24 | [self.view addSubview:tableView];
25 |
26 | UIToolbar *statusBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
27 | [self.view addSubview:statusBar];
28 | }
29 |
30 | - (void)didReceiveMemoryWarning {
31 | [super didReceiveMemoryWarning];
32 | // Dispose of any resources that can be recreated.
33 | }
34 |
35 | @end
36 |
--------------------------------------------------------------------------------
/VVeboTableViewDemoTests/VVeboTableViewDemoTests.m:
--------------------------------------------------------------------------------
1 | //
2 | // VVeboTableViewDemoTests.m
3 | // VVeboTableViewDemoTests
4 | //
5 | // Created by Johnil on 15/5/25.
6 | // Copyright (c) 2015年 Johnil. All rights reserved.
7 | //
8 |
9 | #import
10 | #import
11 |
12 | @interface VVeboTableViewDemoTests : XCTestCase
13 |
14 | @end
15 |
16 | @implementation VVeboTableViewDemoTests
17 |
18 | - (void)setUp {
19 | [super setUp];
20 | // Put setup code here. This method is called before the invocation of each test method in the class.
21 | }
22 |
23 | - (void)tearDown {
24 | // Put teardown code here. This method is called after the invocation of each test method in the class.
25 | [super tearDown];
26 | }
27 |
28 | - (void)testExample {
29 | // This is an example of a functional test case.
30 | XCTAssert(YES, @"Pass");
31 | }
32 |
33 | - (void)testPerformanceExample {
34 | // This is an example of a performance test case.
35 | [self measureBlock:^{
36 | // Put the code you want to measure the time of here.
37 | }];
38 | }
39 |
40 | @end
41 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/Images.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 | }
--------------------------------------------------------------------------------
/VVeboTableViewDemo/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | com.johnil.$(PRODUCT_NAME:rfc1034identifier)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | APPL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 | LSRequiresIPhoneOS
24 |
25 | UILaunchStoryboardName
26 | LaunchScreen
27 | UIMainStoryboardFile
28 | Main
29 | UIRequiredDeviceCapabilities
30 |
31 | armv7
32 |
33 | UISupportedInterfaceOrientations
34 |
35 | UIInterfaceOrientationPortrait
36 |
37 | UISupportedInterfaceOrientations~ipad
38 |
39 | UIInterfaceOrientationPortrait
40 | UIInterfaceOrientationPortraitUpsideDown
41 | UIInterfaceOrientationLandscapeLeft
42 | UIInterfaceOrientationLandscapeRight
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/NSString+Additions.h:
--------------------------------------------------------------------------------
1 | //
2 | // NSString+Additions.h
3 | // Additions
4 | //
5 | // Created by Johnil on 13-6-15.
6 | // Copyright (c) 2013年 Johnil. All rights reserved.
7 | //
8 |
9 | #import
10 | #import
11 | @interface NSString (Additions)
12 |
13 | #pragma mark - java api
14 | - (NSUInteger) compareTo: (NSString*) comp;
15 | - (NSUInteger) compareToIgnoreCase: (NSString*) comp;
16 | - (bool) contains: (NSString*) substring;
17 | - (bool) endsWith: (NSString*) substring;
18 | - (bool) startsWith: (NSString*) substring;
19 | - (NSUInteger) indexOf: (NSString*) substring;
20 | - (NSUInteger) indexOf:(NSString *)substring startingFrom: (NSUInteger) index;
21 | - (NSUInteger) lastIndexOf: (NSString*) substring;
22 | - (NSUInteger) lastIndexOf:(NSString *)substring startingFrom: (NSUInteger) index;
23 | - (NSString*) substringFromIndex:(NSUInteger)from toIndex: (NSUInteger) to;
24 | - (NSString*) trim;
25 | - (NSArray*) split: (NSString*) token;
26 | - (NSString*) replace: (NSString*) target withString: (NSString*) replacement;
27 | - (NSArray*) split: (NSString*) token limit: (NSUInteger) maxResults;
28 |
29 | - (CGSize)sizeWithConstrainedToWidth:(float)width fromFont:(UIFont *)font1 lineSpace:(float)lineSpace;
30 | - (CGSize)sizeWithConstrainedToSize:(CGSize)size fromFont:(UIFont *)font1 lineSpace:(float)lineSpace;
31 | - (void)drawInContext:(CGContextRef)context withPosition:(CGPoint)p andFont:(UIFont *)font andTextColor:(UIColor *)color andHeight:(float)height andWidth:(float)width;
32 | - (void)drawInContext:(CGContextRef)context withPosition:(CGPoint)p andFont:(UIFont *)font andTextColor:(UIColor *)color andHeight:(float)height;
33 |
34 | @end
35 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/AppDelegate.m:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.m
3 | // VVeboTableViewDemo
4 | //
5 | // Created by Johnil on 15/5/25.
6 | // Copyright (c) 2015年 Johnil. 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 | - (void)applicationWillResignActive:(UIApplication *)application {
24 | // 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.
25 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
26 | }
27 |
28 | - (void)applicationDidEnterBackground:(UIApplication *)application {
29 | // 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.
30 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
31 | }
32 |
33 | - (void)applicationWillEnterForeground:(UIApplication *)application {
34 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
35 | }
36 |
37 | - (void)applicationDidBecomeActive:(UIApplication *)application {
38 | // 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.
39 | }
40 |
41 | - (void)applicationWillTerminate:(UIApplication *)application {
42 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
43 | }
44 |
45 | @end
46 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/SDWebImage/UIImage+WebP.m:
--------------------------------------------------------------------------------
1 | //
2 | // UIImage+WebP.m
3 | // SDWebImage
4 | //
5 | // Created by Olivier Poitrey on 07/06/13.
6 | // Copyright (c) 2013 Dailymotion. All rights reserved.
7 | //
8 |
9 | #ifdef SD_WEBP
10 | #import "UIImage+WebP.h"
11 | #import "webp/decode.h"
12 |
13 | // Callback for CGDataProviderRelease
14 | static void FreeImageData(void *info, const void *data, size_t size)
15 | {
16 | free((void *)data);
17 | }
18 |
19 | @implementation UIImage (WebP)
20 |
21 | + (UIImage *)sd_imageWithWebPData:(NSData *)data {
22 | WebPDecoderConfig config;
23 | if (!WebPInitDecoderConfig(&config)) {
24 | return nil;
25 | }
26 |
27 | if (WebPGetFeatures(data.bytes, data.length, &config.input) != VP8_STATUS_OK) {
28 | return nil;
29 | }
30 |
31 | config.output.colorspace = config.input.has_alpha ? MODE_rgbA : MODE_RGB;
32 | config.options.use_threads = 1;
33 |
34 | // Decode the WebP image data into a RGBA value array.
35 | if (WebPDecode(data.bytes, data.length, &config) != VP8_STATUS_OK) {
36 | return nil;
37 | }
38 |
39 | int width = config.input.width;
40 | int height = config.input.height;
41 | if (config.options.use_scaling) {
42 | width = config.options.scaled_width;
43 | height = config.options.scaled_height;
44 | }
45 |
46 | // Construct a UIImage from the decoded RGBA value array.
47 | CGDataProviderRef provider =
48 | CGDataProviderCreateWithData(NULL, config.output.u.RGBA.rgba, config.output.u.RGBA.size, FreeImageData);
49 | CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
50 | CGBitmapInfo bitmapInfo = config.input.has_alpha ? kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast : 0;
51 | size_t components = config.input.has_alpha ? 4 : 3;
52 | CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
53 | CGImageRef imageRef = CGImageCreate(width, height, 8, components * 8, components * width, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
54 |
55 | CGColorSpaceRelease(colorSpaceRef);
56 | CGDataProviderRelease(provider);
57 |
58 | UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
59 | CGImageRelease(imageRef);
60 |
61 | return image;
62 | }
63 |
64 | @end
65 |
66 | #if !COCOAPODS
67 | // Functions to resolve some undefined symbols when using WebP and force_load flag
68 | void WebPInitPremultiplyNEON(void) {}
69 | void WebPInitUpsamplersNEON(void) {}
70 | void VP8DspInitNEON(void) {}
71 | #endif
72 |
73 | #endif
74 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 | * Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
22 | *
23 | * This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
24 | */
25 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage;
26 |
27 | /**
28 | * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
29 | *
30 | * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
31 | */
32 | @property (nonatomic, strong) NSURLCredential *credential;
33 |
34 | /**
35 | * The SDWebImageDownloaderOptions for the receiver.
36 | */
37 | @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options;
38 |
39 | /**
40 | * Initializes a `SDWebImageDownloaderOperation` object
41 | *
42 | * @see SDWebImageDownloaderOperation
43 | *
44 | * @param request the URL request
45 | * @param options downloader options
46 | * @param progressBlock the block executed when a new chunk of data arrives.
47 | * @note the progress block is executed on a background queue
48 | * @param completedBlock the block executed when the download is done.
49 | * @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
50 | * @param cancelBlock the block executed if the download (operation) is cancelled
51 | *
52 | * @return the initialized instance
53 | */
54 | - (id)initWithRequest:(NSURLRequest *)request
55 | options:(SDWebImageDownloaderOptions)options
56 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
57 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock
58 | cancelled:(SDWebImageNoParamsBlock)cancelBlock;
59 |
60 | @end
61 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/UIView+Additions.h:
--------------------------------------------------------------------------------
1 | //
2 | // UIView+Additions.h
3 | // Additions
4 | //
5 | // Created by Johnil on 13-6-7.
6 | // Copyright (c) 2013年 Johnil. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | typedef void(^touchBlock)(UITouch *t, UIView *target);
12 |
13 | @interface UIView (Additions)
14 | - (float)x;
15 | - (float)y;
16 | - (float)width;
17 | - (float)height;
18 |
19 | - (void)setX:(float)x;
20 | - (void)setY:(float)y;
21 | - (void)setWidth:(float)w;
22 | - (void)setHeight:(float)h;
23 |
24 | - (float)boundsWidth;
25 | - (float)boundsHeight;
26 | - (void)setBoundsWidth:(float)w;
27 | - (void)setBoundsHeight:(float)h;
28 | //
29 | //- (void)fadeIn;
30 | //- (void)fadeOut;
31 | //- (void)fadeInOnComplet:(void(^)(BOOL f))complet;
32 | //- (void)fadeOutOnComplet:(void(^)(BOOL f))complet;
33 | //
34 | //- (void)removeAllSubviews;
35 | //- (void)removeSubviewWithTag:(NSInteger)tag;
36 | //- (void)removeSubviewExceptTag:(NSInteger)tag;
37 | //- (void)removeSubviewExceptClass:(Class)class1;
38 | //
39 | //- (UIImage *)toAlphaRetinaImageRealTime;
40 | //- (UIImage *)toRetinaImage;
41 | //- (UIImage *)toAlphaRetinaImage;
42 | //- (UIImage *)toImage;
43 | //- (UIImage *)toImagewhithAlpha:(BOOL)alpha;
44 | //- (UIImage *)toImageWithRect:(CGRect)frame;
45 | //- (UIImage *)toImageWithRect:(CGRect)frame withAlpha:(BOOL)alpha;
46 | //- (UIImage *)visbleToImage;
47 | //
48 | //- (void)addWhiteView;
49 | //- (void)addWhiteViewWithAlpha:(float)alpha;
50 | //- (void)addBlackView;
51 | //- (void)addShadowWithColor:(UIColor *)color;
52 | //- (void)addShadow;
53 | //- (void)addShadowWithAlpha:(float)alpha;
54 | //- (void)removeShadow;
55 | //- (UIView *)findAndResignFirstResponder;
56 | //- (void)addBorder;
57 | //- (UIView *)addLine:(UIColor *)color frame:(CGRect)frame;
58 | //
59 | //- (void)addCorner;
60 | //- (void)shake:(float)range;
61 | //- (void)shakeRepeat:(float)range;
62 | //- (void)shakeX:(float)range;
63 | //- (void)rasterize;
64 | //
65 | //+ (void)vveboAnimations:(void (^)(void))animations;
66 | //+ (void)vveboAnimations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;
67 | //
68 | //+ (void)vveboAnimateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations;
69 | //+ (void)vveboAnimateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;
70 | //+ (void)vveboAnimateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;
71 | //+ (void)vveboAnimateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;
72 | //
73 | //- (void)addLine:(CGRect)rect;
74 | //- (BOOL)hasActionSheetOrAlert;
75 | //- (UIView *)subviewWithTag:(NSInteger)tag;
76 | @end
77 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/UIScreen+Additions.m:
--------------------------------------------------------------------------------
1 | //
2 | // UIScreen+Additions.m
3 | // Additions
4 | //
5 | // Created by Johnil on 13-6-15.
6 | // Copyright (c) 2013年 Johnil. All rights reserved.
7 | //
8 |
9 | #import "UIScreen+Additions.h"
10 |
11 | @implementation UIScreen (Additions)
12 |
13 | + (float)screenWidth{
14 | if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
15 | if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {
16 | return [UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale;
17 | } else {
18 | return [UIScreen mainScreen].bounds.size.height;
19 | }
20 | } else {
21 | if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {
22 | return [UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale;
23 | } else {
24 | return [UIScreen mainScreen].bounds.size.width;
25 | }
26 | }
27 | }
28 |
29 | + (float)screenHeight{
30 | if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
31 | if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {
32 | if ([UIApplication sharedApplication].statusBarFrame.size.width>20) {
33 | return [UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale-20;
34 | }
35 | return [UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale;
36 | } else {
37 | if ([UIApplication sharedApplication].statusBarFrame.size.width>20) {
38 | return [UIScreen mainScreen].bounds.size.width-20;
39 | }
40 | return [UIScreen mainScreen].bounds.size.width;
41 | }
42 | } else {
43 | if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {
44 | if ([UIApplication sharedApplication].statusBarFrame.size.height>20) {
45 | return [UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale-20;
46 | }
47 | return [UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale;
48 | } else {
49 | if ([UIApplication sharedApplication].statusBarFrame.size.height>20) {
50 | return [UIScreen mainScreen].bounds.size.height-20;
51 | }
52 | return [UIScreen mainScreen].bounds.size.height;
53 | }
54 | }
55 | }
56 |
57 | + (BOOL)isRetina{
58 | if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {
59 | return [UIScreen mainScreen].nativeScale>=2;
60 | } else {
61 | return [UIScreen mainScreen].scale>=2;
62 | }
63 | }
64 |
65 | + (float)scale{
66 | if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {
67 | return [UIScreen mainScreen].nativeScale;
68 | } else {
69 | return [UIScreen mainScreen].scale;
70 | }
71 | }
72 |
73 | @end
74 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/SDWebImage/MKAnnotationView+WebCache.m:
--------------------------------------------------------------------------------
1 | //
2 | // MKAnnotationView+WebCache.m
3 | // SDWebImage
4 | //
5 | // Created by Olivier Poitrey on 14/03/12.
6 | // Copyright (c) 2012 Dailymotion. All rights reserved.
7 | //
8 |
9 | #import "MKAnnotationView+WebCache.h"
10 | #import "objc/runtime.h"
11 | #import "UIView+WebCacheOperation.h"
12 |
13 | static char imageURLKey;
14 |
15 | @implementation MKAnnotationView (WebCache)
16 |
17 | - (NSURL *)sd_imageURL {
18 | return objc_getAssociatedObject(self, &imageURLKey);
19 | }
20 |
21 | - (void)sd_setImageWithURL:(NSURL *)url {
22 | [self sd_setImageWithURL:url placeholderImage:nil options:0 completed:nil];
23 | }
24 |
25 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
26 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 completed:nil];
27 | }
28 |
29 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
30 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options completed:nil];
31 | }
32 |
33 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock {
34 | [self sd_setImageWithURL:url placeholderImage:nil options:0 completed:completedBlock];
35 | }
36 |
37 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
38 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 completed:completedBlock];
39 | }
40 |
41 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
42 | [self sd_cancelCurrentImageLoad];
43 |
44 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
45 | self.image = placeholder;
46 |
47 | if (url) {
48 | __weak MKAnnotationView *wself = self;
49 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
50 | if (!wself) return;
51 | dispatch_main_sync_safe(^{
52 | __strong MKAnnotationView *sself = wself;
53 | if (!sself) return;
54 | if (image) {
55 | sself.image = image;
56 | }
57 | if (completedBlock && finished) {
58 | completedBlock(image, error, cacheType, url);
59 | }
60 | });
61 | }];
62 | [self sd_setImageLoadOperation:operation forKey:@"MKAnnotationViewImage"];
63 | } else {
64 | dispatch_main_async_safe(^{
65 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
66 | if (completedBlock) {
67 | completedBlock(nil, error, SDImageCacheTypeNone, url);
68 | }
69 | });
70 | }
71 | }
72 |
73 | - (void)sd_cancelCurrentImageLoad {
74 | [self sd_cancelImageLoadOperationWithKey:@"MKAnnotationViewImage"];
75 | }
76 |
77 | @end
78 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/Base.lproj/LaunchScreen.xib:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
20 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 | @property (weak, nonatomic) id delegate;
62 |
63 | /**
64 | * Return the global image prefetcher instance.
65 | */
66 | + (SDWebImagePrefetcher *)sharedImagePrefetcher;
67 |
68 | /**
69 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching,
70 | * currently one image is downloaded at a time,
71 | * and skips images for failed downloads and proceed to the next image in the list
72 | *
73 | * @param urls list of URLs to prefetch
74 | */
75 | - (void)prefetchURLs:(NSArray *)urls;
76 |
77 | /**
78 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching,
79 | * currently one image is downloaded at a time,
80 | * and skips images for failed downloads and proceed to the next image in the list
81 | *
82 | * @param urls list of URLs to prefetch
83 | * @param progressBlock block to be called when progress updates;
84 | * first parameter is the number of completed (successful or not) requests,
85 | * second parameter is the total number of images originally requested to be prefetched
86 | * @param completionBlock block to be called when prefetching is completed
87 | * first param is the number of completed (successful or not) requests,
88 | * second parameter is the number of skipped requests
89 | */
90 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock;
91 |
92 | /**
93 | * Remove and cancel queued list
94 | */
95 | - (void)cancelPrefetching;
96 |
97 |
98 | @end
99 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/SDWebImage/MKAnnotationView+WebCache.h:
--------------------------------------------------------------------------------
1 | //
2 | // MKAnnotationView+WebCache.h
3 | // SDWebImage
4 | //
5 | // Created by Olivier Poitrey on 14/03/12.
6 | // Copyright (c) 2012 Dailymotion. All rights reserved.
7 | //
8 |
9 | #import "MapKit/MapKit.h"
10 | #import "SDWebImageManager.h"
11 |
12 | /**
13 | * Integrates SDWebImage async downloading and caching of remote images with MKAnnotationView.
14 | */
15 | @interface MKAnnotationView (WebCache)
16 |
17 | /**
18 | * Get the current image URL.
19 | *
20 | * Note that because of the limitations of categories this property can get out of sync
21 | * if you use sd_setImage: directly.
22 | */
23 | - (NSURL *)sd_imageURL;
24 |
25 | /**
26 | * Set the imageView `image` with an `url`.
27 | *
28 | * The download is asynchronous and cached.
29 | *
30 | * @param url The url for the image.
31 | */
32 | - (void)sd_setImageWithURL:(NSURL *)url;
33 |
34 | /**
35 | * Set the imageView `image` with an `url` and a placeholder.
36 | *
37 | * The download is asynchronous and cached.
38 | *
39 | * @param url The url for the image.
40 | * @param placeholder The image to be set initially, until the image request finishes.
41 | * @see sd_setImageWithURL:placeholderImage:options:
42 | */
43 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;
44 |
45 | /**
46 | * Set the imageView `image` with an `url`, placeholder and custom options.
47 | *
48 | * The download is asynchronous and cached.
49 | *
50 | * @param url The url for the image.
51 | * @param placeholder The image to be set initially, until the image request finishes.
52 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
53 | */
54 |
55 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
56 |
57 | /**
58 | * Set the imageView `image` with an `url`.
59 | *
60 | * The download is asynchronous and cached.
61 | *
62 | * @param url The url for the image.
63 | * @param completedBlock A block called when operation has been completed. This block has no return value
64 | * and takes the requested UIImage as first parameter. In case of error the image parameter
65 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
66 | * indicating if the image was retrived from the local cache or from the network.
67 | * The fourth parameter is the original image url.
68 | */
69 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock;
70 |
71 | /**
72 | * Set the imageView `image` with an `url`, placeholder.
73 | *
74 | * The download is asynchronous and cached.
75 | *
76 | * @param url The url for the image.
77 | * @param placeholder The image to be set initially, until the image request finishes.
78 | * @param completedBlock A block called when operation has been completed. This block has no return value
79 | * and takes the requested UIImage as first parameter. In case of error the image parameter
80 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
81 | * indicating if the image was retrived from the local cache or from the network.
82 | * The fourth parameter is the original image url.
83 | */
84 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
85 |
86 | /**
87 | * Set the imageView `image` with an `url`, placeholder and custom options.
88 | *
89 | * The download is asynchronous and cached.
90 | *
91 | * @param url The url for the image.
92 | * @param placeholder The image to be set initially, until the image request finishes.
93 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
94 | * @param completedBlock A block called when operation has been completed. This block has no return value
95 | * and takes the requested UIImage as first parameter. In case of error the image parameter
96 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
97 | * indicating if the image was retrived from the local cache or from the network.
98 | * The fourth parameter is the original image url.
99 | */
100 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
101 |
102 | /**
103 | * Cancel the current download
104 | */
105 | - (void)sd_cancelCurrentImageLoad;
106 |
107 | @end
108 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 | self.maxConcurrentDownloads = 3;
44 | }
45 | return self;
46 | }
47 |
48 | - (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads {
49 | self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads;
50 | }
51 |
52 | - (NSUInteger)maxConcurrentDownloads {
53 | return self.manager.imageDownloader.maxConcurrentDownloads;
54 | }
55 |
56 | - (void)startPrefetchingAtIndex:(NSUInteger)index {
57 | if (index >= self.prefetchURLs.count) return;
58 | self.requestedCount++;
59 | [self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
60 | if (!finished) return;
61 | self.finishedCount++;
62 |
63 | if (image) {
64 | if (self.progressBlock) {
65 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]);
66 | }
67 | NSLog(@"Prefetched %@ out of %@", @(self.finishedCount), @(self.prefetchURLs.count));
68 | }
69 | else {
70 | if (self.progressBlock) {
71 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]);
72 | }
73 | NSLog(@"Prefetched %@ out of %@ (Failed)", @(self.finishedCount), @(self.prefetchURLs.count));
74 |
75 | // Add last failed
76 | self.skippedCount++;
77 | }
78 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) {
79 | [self.delegate imagePrefetcher:self
80 | didPrefetchURL:self.prefetchURLs[index]
81 | finishedCount:self.finishedCount
82 | totalCount:self.prefetchURLs.count
83 | ];
84 | }
85 |
86 | if (self.prefetchURLs.count > self.requestedCount) {
87 | dispatch_async(dispatch_get_main_queue(), ^{
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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 | };
55 |
56 | typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) {
57 | /**
58 | * Default value. All download operations will execute in queue style (first-in-first-out).
59 | */
60 | SDWebImageDownloaderFIFOExecutionOrder,
61 |
62 | /**
63 | * All download operations will execute in stack style (last-in-first-out).
64 | */
65 | SDWebImageDownloaderLIFOExecutionOrder
66 | };
67 |
68 | extern NSString *const SDWebImageDownloadStartNotification;
69 | extern NSString *const SDWebImageDownloadStopNotification;
70 |
71 | typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize);
72 |
73 | typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished);
74 |
75 | typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers);
76 |
77 | /**
78 | * Asynchronous downloader dedicated and optimized for image loading.
79 | */
80 | @interface SDWebImageDownloader : NSObject
81 |
82 | @property (assign, nonatomic) NSInteger maxConcurrentDownloads;
83 |
84 | /**
85 | * Shows the current amount of downloads that still need to be downloaded
86 | */
87 |
88 | @property (readonly, nonatomic) NSUInteger currentDownloadCount;
89 |
90 |
91 | /**
92 | * The timeout value (in seconds) for the download operation. Default: 15.0.
93 | */
94 | @property (assign, nonatomic) NSTimeInterval downloadTimeout;
95 |
96 |
97 | /**
98 | * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`.
99 | */
100 | @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder;
101 |
102 | /**
103 | * Singleton method, returns the shared instance
104 | *
105 | * @return global shared instance of downloader class
106 | */
107 | + (SDWebImageDownloader *)sharedDownloader;
108 |
109 | /**
110 | * Set username
111 | */
112 | @property (strong, nonatomic) NSString *username;
113 |
114 | /**
115 | * Set password
116 | */
117 | @property (strong, nonatomic) NSString *password;
118 |
119 | /**
120 | * Set filter to pick headers for downloading image HTTP request.
121 | *
122 | * This block will be invoked for each downloading image request, returned
123 | * NSDictionary will be used as headers in corresponding HTTP request.
124 | */
125 | @property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter;
126 |
127 | /**
128 | * Set a value for a HTTP header to be appended to each download HTTP request.
129 | *
130 | * @param value The value for the header field. Use `nil` value to remove the header.
131 | * @param field The name of the header field to set.
132 | */
133 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
134 |
135 | /**
136 | * Returns the value of the specified HTTP header field.
137 | *
138 | * @return The value associated with the header field field, or `nil` if there is no corresponding header field.
139 | */
140 | - (NSString *)valueForHTTPHeaderField:(NSString *)field;
141 |
142 | /**
143 | * Sets a subclass of `SDWebImageDownloaderOperation` as the default
144 | * `NSOperation` to be used each time SDWebImage constructs a request
145 | * operation to download an image.
146 | *
147 | * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set
148 | * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`.
149 | */
150 | - (void)setOperationClass:(Class)operationClass;
151 |
152 | /**
153 | * Creates a SDWebImageDownloader async downloader instance with a given URL
154 | *
155 | * The delegate will be informed when the image is finish downloaded or an error has happen.
156 | *
157 | * @see SDWebImageDownloaderDelegate
158 | *
159 | * @param url The URL to the image to download
160 | * @param options The options to be used for this download
161 | * @param progressBlock A block called repeatedly while the image is downloading
162 | * @param completedBlock A block called once the download is completed.
163 | * If the download succeeded, the image parameter is set, in case of error,
164 | * error parameter is set with the error. The last parameter is always YES
165 | * if SDWebImageDownloaderProgressiveDownload isn't use. With the
166 | * SDWebImageDownloaderProgressiveDownload option, this block is called
167 | * repeatedly with the partial image object and the finished argument set to NO
168 | * before to be called a last time with the full image and finished argument
169 | * set to YES. In case of error, the finished argument is always YES.
170 | *
171 | * @return A cancellable SDWebImageOperation
172 | */
173 | - (id )downloadImageWithURL:(NSURL *)url
174 | options:(SDWebImageDownloaderOptions)options
175 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
176 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock;
177 |
178 | /**
179 | * Sets the download queue suspension state
180 | */
181 | - (void)setSuspended:(BOOL)suspended;
182 |
183 | @end
184 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/SDWebImage/UIButton+WebCache.m:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "UIButton+WebCache.h"
10 | #import "objc/runtime.h"
11 | #import "UIView+WebCacheOperation.h"
12 |
13 | static char imageURLStorageKey;
14 |
15 | @implementation UIButton (WebCache)
16 |
17 | - (NSURL *)sd_currentImageURL {
18 | NSURL *url = self.imageURLStorage[@(self.state)];
19 |
20 | if (!url) {
21 | url = self.imageURLStorage[@(UIControlStateNormal)];
22 | }
23 |
24 | return url;
25 | }
26 |
27 | - (NSURL *)sd_imageURLForState:(UIControlState)state {
28 | return self.imageURLStorage[@(state)];
29 | }
30 |
31 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state {
32 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
33 | }
34 |
35 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
36 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
37 | }
38 |
39 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
40 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
41 | }
42 |
43 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock {
44 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
45 | }
46 |
47 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
48 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
49 | }
50 |
51 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
52 |
53 | [self setImage:placeholder forState:state];
54 | [self sd_cancelImageLoadForState:state];
55 |
56 | if (!url) {
57 | [self.imageURLStorage removeObjectForKey:@(state)];
58 |
59 | dispatch_main_async_safe(^{
60 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
61 | if (completedBlock) {
62 | completedBlock(nil, error, SDImageCacheTypeNone, url);
63 | }
64 | });
65 |
66 | return;
67 | }
68 |
69 | self.imageURLStorage[@(state)] = url;
70 |
71 | __weak UIButton *wself = self;
72 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
73 | if (!wself) return;
74 | dispatch_main_sync_safe(^{
75 | __strong UIButton *sself = wself;
76 | if (!sself) return;
77 | if (image) {
78 | [sself setImage:image forState:state];
79 | }
80 | if (completedBlock && finished) {
81 | completedBlock(image, error, cacheType, url);
82 | }
83 | });
84 | }];
85 | [self sd_setImageLoadOperation:operation forState:state];
86 | }
87 |
88 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state {
89 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
90 | }
91 |
92 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
93 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
94 | }
95 |
96 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
97 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
98 | }
99 |
100 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock {
101 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
102 | }
103 |
104 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
105 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
106 | }
107 |
108 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
109 | [self sd_cancelImageLoadForState:state];
110 |
111 | [self setBackgroundImage:placeholder forState:state];
112 |
113 | if (url) {
114 | __weak UIButton *wself = self;
115 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
116 | if (!wself) return;
117 | dispatch_main_sync_safe(^{
118 | __strong UIButton *sself = wself;
119 | if (!sself) return;
120 | if (image) {
121 | [sself setBackgroundImage:image forState:state];
122 | }
123 | if (completedBlock && finished) {
124 | completedBlock(image, error, cacheType, url);
125 | }
126 | });
127 | }];
128 | [self sd_setBackgroundImageLoadOperation:operation forState:state];
129 | } else {
130 | dispatch_main_async_safe(^{
131 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
132 | if (completedBlock) {
133 | completedBlock(nil, error, SDImageCacheTypeNone, url);
134 | }
135 | });
136 | }
137 | }
138 |
139 | - (void)sd_setImageLoadOperation:(id)operation forState:(UIControlState)state {
140 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]];
141 | }
142 |
143 | - (void)sd_cancelImageLoadForState:(UIControlState)state {
144 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]];
145 | }
146 |
147 | - (void)sd_setBackgroundImageLoadOperation:(id)operation forState:(UIControlState)state {
148 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]];
149 | }
150 |
151 | - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state {
152 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]];
153 | }
154 |
155 | - (NSMutableDictionary *)imageURLStorage {
156 | NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey);
157 | if (!storage)
158 | {
159 | storage = [NSMutableDictionary dictionary];
160 | objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
161 | }
162 |
163 | return storage;
164 | }
165 |
166 | @end
167 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 | * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory.
41 | */
42 | @property (assign, nonatomic) NSUInteger maxMemoryCost;
43 |
44 | /**
45 | * The maximum length of time to keep an image in the cache, in seconds
46 | */
47 | @property (assign, nonatomic) NSInteger maxCacheAge;
48 |
49 | /**
50 | * The maximum size of the cache, in bytes.
51 | */
52 | @property (assign, nonatomic) NSUInteger maxCacheSize;
53 |
54 | /**
55 | * Returns global shared cache instance
56 | *
57 | * @return SDImageCache global instance
58 | */
59 | + (SDImageCache *)sharedImageCache;
60 |
61 | /**
62 | * Init a new cache store with a specific namespace
63 | *
64 | * @param ns The namespace to use for this cache store
65 | */
66 | - (id)initWithNamespace:(NSString *)ns;
67 |
68 | /**
69 | * Add a read-only cache path to search for images pre-cached by SDImageCache
70 | * Useful if you want to bundle pre-loaded images with your app
71 | *
72 | * @param path The path to use for this read-only cache path
73 | */
74 | - (void)addReadOnlyCachePath:(NSString *)path;
75 |
76 | /**
77 | * Store an image into memory and disk cache at the given key.
78 | *
79 | * @param image The image to store
80 | * @param key The unique image cache key, usually it's image absolute URL
81 | */
82 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key;
83 |
84 | /**
85 | * Store an image into memory and optionally disk cache at the given key.
86 | *
87 | * @param image The image to store
88 | * @param key The unique image cache key, usually it's image absolute URL
89 | * @param toDisk Store the image to disk cache if YES
90 | */
91 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;
92 |
93 | /**
94 | * Store an image into memory and optionally disk cache at the given key.
95 | *
96 | * @param image The image to store
97 | * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage
98 | * @param imageData The image data as returned by the server, this representation will be used for disk storage
99 | * instead of converting the given image object into a storable/compressed image format in order
100 | * to save quality and CPU
101 | * @param key The unique image cache key, usually it's image absolute URL
102 | * @param toDisk Store the image to disk cache if YES
103 | */
104 | - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk;
105 |
106 | /**
107 | * Query the disk cache asynchronously.
108 | *
109 | * @param key The unique key used to store the wanted image
110 | */
111 | - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;
112 |
113 | /**
114 | * Query the memory cache synchronously.
115 | *
116 | * @param key The unique key used to store the wanted image
117 | */
118 | - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;
119 |
120 | /**
121 | * Query the disk cache synchronously after checking the memory cache.
122 | *
123 | * @param key The unique key used to store the wanted image
124 | */
125 | - (UIImage *)imageFromDiskCacheForKey:(NSString *)key;
126 |
127 | /**
128 | * Remove the image from memory and disk cache synchronously
129 | *
130 | * @param key The unique image cache key
131 | */
132 | - (void)removeImageForKey:(NSString *)key;
133 |
134 |
135 | /**
136 | * Remove the image from memory and disk cache synchronously
137 | *
138 | * @param key The unique image cache key
139 | * @param completion An block that should be executed after the image has been removed (optional)
140 | */
141 | - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion;
142 |
143 | /**
144 | * Remove the image from memory and optionally disk cache synchronously
145 | *
146 | * @param key The unique image cache key
147 | * @param fromDisk Also remove cache entry from disk if YES
148 | */
149 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;
150 |
151 | /**
152 | * Remove the image from memory and optionally disk cache synchronously
153 | *
154 | * @param key The unique image cache key
155 | * @param fromDisk Also remove cache entry from disk if YES
156 | * @param completion An block that should be executed after the image has been removed (optional)
157 | */
158 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion;
159 |
160 | /**
161 | * Clear all memory cached images
162 | */
163 | - (void)clearMemory;
164 |
165 | /**
166 | * Clear all disk cached images. Non-blocking method - returns immediately.
167 | * @param completion An block that should be executed after cache expiration completes (optional)
168 | */
169 | - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion;
170 |
171 | /**
172 | * Clear all disk cached images
173 | * @see clearDiskOnCompletion:
174 | */
175 | - (void)clearDisk;
176 |
177 | /**
178 | * Remove all expired cached image from disk. Non-blocking method - returns immediately.
179 | * @param completionBlock An block that should be executed after cache expiration completes (optional)
180 | */
181 | - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock;
182 |
183 | /**
184 | * Remove all expired cached image from disk
185 | * @see cleanDiskWithCompletionBlock:
186 | */
187 | - (void)cleanDisk;
188 |
189 | /**
190 | * Get the size used by the disk cache
191 | */
192 | - (NSUInteger)getSize;
193 |
194 | /**
195 | * Get the number of images in the disk cache
196 | */
197 | - (NSUInteger)getDiskCount;
198 |
199 | /**
200 | * Asynchronously calculate the disk cache's size.
201 | */
202 | - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock;
203 |
204 | /**
205 | * Async check if image exists in disk cache already (does not load the image)
206 | *
207 | * @param key the key describing the url
208 | * @param completionBlock the block to be executed when the check is done.
209 | * @note the completion block will be always executed on the main queue
210 | */
211 | - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
212 |
213 | /**
214 | * Check if image exists in disk cache already (does not load the image)
215 | *
216 | * @param key the key describing the url
217 | *
218 | * @return YES if an image exists for the given key
219 | */
220 | - (BOOL)diskImageExistsWithKey:(NSString *)key;
221 |
222 | /**
223 | * Get the cache path for a certain key (needs the cache path root folder)
224 | *
225 | * @param key the key (can be obtained from url using cacheKeyForURL)
226 | * @param path the cach path root folder
227 | *
228 | * @return the cache path
229 | */
230 | - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path;
231 |
232 | /**
233 | * Get the default cache path for a certain key
234 | *
235 | * @param key the key (can be obtained from url using cacheKeyForURL)
236 | *
237 | * @return the default cache path
238 | */
239 | - (NSString *)defaultCachePathForKey:(NSString *)key;
240 |
241 | @end
242 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/NSString+Additions.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSString+Additions.m
3 | // Additions
4 | //
5 | // Created by Johnil on 13-6-15.
6 | // Copyright (c) 2013年 Johnil. All rights reserved.
7 | //
8 |
9 | #import "NSString+Additions.h"
10 | #import
11 |
12 | @implementation NSString (Additions)
13 |
14 | #pragma mark - java api
15 |
16 | - (NSUInteger) compareTo: (NSString*) comp {
17 | NSComparisonResult result = [self compare:comp];
18 | if (result == NSOrderedSame) {
19 | return 0;
20 | }
21 | return result == NSOrderedAscending ? -1 : 1;
22 | }
23 |
24 | - (NSUInteger) compareToIgnoreCase: (NSString*) comp {
25 | return [[self lowercaseString] compareTo:[comp lowercaseString]];
26 | }
27 |
28 | - (bool) contains: (NSString*) substring {
29 | NSRange range = [self rangeOfString:substring];
30 | return range.location != NSNotFound;
31 | }
32 |
33 | - (bool) endsWith: (NSString*) substring {
34 | NSRange range = [self rangeOfString:substring];
35 | return range.location == [self length] - [substring length];
36 | }
37 |
38 | - (bool) startsWith: (NSString*) substring {
39 | NSRange range = [self rangeOfString:substring];
40 | return range.location == 0;
41 | }
42 |
43 | - (NSUInteger) indexOf: (NSString*) substring {
44 | NSRange range = [self rangeOfString:substring options:NSCaseInsensitiveSearch];
45 | return range.location == NSNotFound ? -1 : range.location;
46 | }
47 |
48 | - (NSUInteger) indexOf:(NSString *)substring startingFrom: (NSUInteger) index {
49 | NSString* test = [self substringFromIndex:index];
50 | return index+[test indexOf:substring];
51 | }
52 |
53 | - (NSUInteger) lastIndexOf: (NSString*) substring {
54 | NSRange range = [self rangeOfString:substring options:NSBackwardsSearch];
55 | return range.location == NSNotFound ? -1 : range.location;
56 | }
57 |
58 | - (NSUInteger) lastIndexOf:(NSString *)substring startingFrom: (NSUInteger) index {
59 | NSString* test = [self substringFromIndex:index];
60 | return [test lastIndexOf:substring];
61 | }
62 |
63 | - (NSString*) substringFromIndex:(NSUInteger)from toIndex: (NSUInteger) to {
64 | NSRange range;
65 | range.location = from;
66 | range.length = to - from;
67 | return [self substringWithRange: range];
68 | }
69 |
70 | - (NSString*) trim {
71 |
72 | return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
73 | }
74 |
75 | - (NSArray*) split: (NSString*) token {
76 | return [self split:token limit:0];
77 | }
78 |
79 | - (NSArray*) split: (NSString*) token limit: (NSUInteger) maxResults {
80 | NSMutableArray* result = [NSMutableArray arrayWithCapacity: 8];
81 | NSString* buffer = self;
82 | while ([buffer contains:token]) {
83 | if (maxResults > 0 && [result count] == maxResults - 1) {
84 | break;
85 | }
86 | NSUInteger matchIndex = [buffer indexOf:token];
87 | NSString* nextPart = [buffer substringFromIndex:0 toIndex:matchIndex];
88 | buffer = [buffer substringFromIndex:matchIndex + [token length]];
89 | [result addObject:nextPart];
90 | }
91 | if ([buffer length] > 0) {
92 | [result addObject:buffer];
93 | }
94 |
95 | return result;
96 | }
97 |
98 | - (NSString*) replace: (NSString*) target withString: (NSString*) replacement {
99 | return [self stringByReplacingOccurrencesOfString:target withString:replacement];
100 | }
101 |
102 | - (CGSize)sizeWithConstrainedToWidth:(float)width fromFont:(UIFont *)font1 lineSpace:(float)lineSpace{
103 | return [self sizeWithConstrainedToSize:CGSizeMake(width, CGFLOAT_MAX) fromFont:font1 lineSpace:lineSpace];
104 | }
105 |
106 | - (CGSize)sizeWithConstrainedToSize:(CGSize)size fromFont:(UIFont *)font1 lineSpace:(float)lineSpace{
107 | CGFloat minimumLineHeight = font1.pointSize,maximumLineHeight = minimumLineHeight, linespace = lineSpace;
108 | CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)font1.fontName,font1.pointSize,NULL);
109 | CTLineBreakMode lineBreakMode = kCTLineBreakByWordWrapping;
110 | //Apply paragraph settings
111 | CTTextAlignment alignment = kCTLeftTextAlignment;
112 | CTParagraphStyleRef style = CTParagraphStyleCreate((CTParagraphStyleSetting[6]){
113 | {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment},
114 | {kCTParagraphStyleSpecifierMinimumLineHeight,sizeof(minimumLineHeight),&minimumLineHeight},
115 | {kCTParagraphStyleSpecifierMaximumLineHeight,sizeof(maximumLineHeight),&maximumLineHeight},
116 | {kCTParagraphStyleSpecifierMaximumLineSpacing, sizeof(linespace), &linespace},
117 | {kCTParagraphStyleSpecifierMinimumLineSpacing, sizeof(linespace), &linespace},
118 | {kCTParagraphStyleSpecifierLineBreakMode,sizeof(CTLineBreakMode),&lineBreakMode}
119 | },6);
120 | NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)font,(NSString*)kCTFontAttributeName,(__bridge id)style,(NSString*)kCTParagraphStyleAttributeName,nil];
121 | NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self attributes:attributes];
122 | // [self clearEmoji:string start:0 font:font1];
123 | CFAttributedStringRef attributedString = (__bridge CFAttributedStringRef)string;
124 | CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
125 | CGSize result = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [string length]), NULL, size, NULL);
126 | CFRelease(framesetter);
127 | CFRelease(font);
128 | CFRelease(style);
129 | string = nil;
130 | attributes = nil;
131 | return result;
132 | }
133 |
134 | - (void)drawInContext:(CGContextRef)context withPosition:(CGPoint)p andFont:(UIFont *)font andTextColor:(UIColor *)color andHeight:(float)height andWidth:(float)width{
135 | CGSize size = CGSizeMake(width, font.pointSize+10);
136 | CGContextSetTextMatrix(context,CGAffineTransformIdentity);
137 | CGContextTranslateCTM(context,0,height);
138 | CGContextScaleCTM(context,1.0,-1.0);
139 |
140 | //Determine default text color
141 | UIColor* textColor = color;
142 | //Set line height, font, color and break mode
143 | CTFontRef font1 = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize,NULL);
144 | //Apply paragraph settings
145 | CGFloat minimumLineHeight = font.pointSize,maximumLineHeight = minimumLineHeight+10, linespace = 5;
146 | CTLineBreakMode lineBreakMode = kCTLineBreakByTruncatingTail;
147 | CTTextAlignment alignment = kCTLeftTextAlignment;
148 | //Apply paragraph settings
149 | CTParagraphStyleRef style = CTParagraphStyleCreate((CTParagraphStyleSetting[6]){
150 | {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment},
151 | {kCTParagraphStyleSpecifierMinimumLineHeight,sizeof(minimumLineHeight),&minimumLineHeight},
152 | {kCTParagraphStyleSpecifierMaximumLineHeight,sizeof(maximumLineHeight),&maximumLineHeight},
153 | {kCTParagraphStyleSpecifierMaximumLineSpacing, sizeof(linespace), &linespace},
154 | {kCTParagraphStyleSpecifierMinimumLineSpacing, sizeof(linespace), &linespace},
155 | {kCTParagraphStyleSpecifierLineBreakMode,sizeof(CTLineBreakMode),&lineBreakMode}
156 | },6);
157 |
158 | NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)font1,(NSString*)kCTFontAttributeName,
159 | textColor.CGColor,kCTForegroundColorAttributeName,
160 | style,kCTParagraphStyleAttributeName,
161 | nil];
162 | //Create path to work with a frame with applied margins
163 | CGMutablePathRef path = CGPathCreateMutable();
164 | CGPathAddRect(path,NULL,CGRectMake(p.x, height-p.y-size.height,(size.width),(size.height)));
165 |
166 | //Create attributed string, with applied syntax highlighting
167 | NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:self attributes:attributes];
168 | CFAttributedStringRef attributedString = (__bridge CFAttributedStringRef)attributedStr;
169 |
170 | //Draw the frame
171 | CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
172 | CTFrameRef ctframe = CTFramesetterCreateFrame(framesetter, CFRangeMake(0,CFAttributedStringGetLength(attributedString)),path,NULL);
173 | CTFrameDraw(ctframe,context);
174 | CGPathRelease(path);
175 | CFRelease(font1);
176 | CFRelease(framesetter);
177 | CFRelease(ctframe);
178 | [[attributedStr mutableString] setString:@""];
179 | CGContextSetTextMatrix(context,CGAffineTransformIdentity);
180 | CGContextTranslateCTM(context,0, height);
181 | CGContextScaleCTM(context,1.0,-1.0);
182 | }
183 |
184 | - (void)drawInContext:(CGContextRef)context withPosition:(CGPoint)p andFont:(UIFont *)font andTextColor:(UIColor *)color andHeight:(float)height{
185 | [self drawInContext:context withPosition:p andFont:font andTextColor:color andHeight:height andWidth:CGFLOAT_MAX];
186 | }
187 |
188 | @end
189 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/SDWebImage/UIButton+WebCache.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "SDWebImageCompat.h"
10 | #import "SDWebImageManager.h"
11 |
12 | /**
13 | * Integrates SDWebImage async downloading and caching of remote images with UIButtonView.
14 | */
15 | @interface UIButton (WebCache)
16 |
17 | /**
18 | * Get the current image URL.
19 | */
20 | - (NSURL *)sd_currentImageURL;
21 |
22 | /**
23 | * Get the image URL for a control state.
24 | *
25 | * @param state Which state you want to know the URL for. The values are described in UIControlState.
26 | */
27 | - (NSURL *)sd_imageURLForState:(UIControlState)state;
28 |
29 | /**
30 | * Set the imageView `image` with an `url`.
31 | *
32 | * The download is asynchronous and cached.
33 | *
34 | * @param url The url for the image.
35 | * @param state The state that uses the specified title. The values are described in UIControlState.
36 | */
37 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state;
38 |
39 | /**
40 | * Set the imageView `image` with an `url` and a placeholder.
41 | *
42 | * The download is asynchronous and cached.
43 | *
44 | * @param url The url for the image.
45 | * @param state The state that uses the specified title. The values are described in UIControlState.
46 | * @param placeholder The image to be set initially, until the image request finishes.
47 | * @see sd_setImageWithURL:placeholderImage:options:
48 | */
49 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder;
50 |
51 | /**
52 | * Set the imageView `image` with an `url`, placeholder and custom options.
53 | *
54 | * The download is asynchronous and cached.
55 | *
56 | * @param url The url for the image.
57 | * @param state The state that uses the specified title. The values are described in UIControlState.
58 | * @param placeholder The image to be set initially, until the image request finishes.
59 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
60 | */
61 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
62 |
63 | /**
64 | * Set the imageView `image` with an `url`.
65 | *
66 | * The download is asynchronous and cached.
67 | *
68 | * @param url The url for the image.
69 | * @param state The state that uses the specified title. The values are described in UIControlState.
70 | * @param completedBlock A block called when operation has been completed. This block has no return value
71 | * and takes the requested UIImage as first parameter. In case of error the image parameter
72 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
73 | * indicating if the image was retrived from the local cache or from the network.
74 | * The fourth parameter is the original image url.
75 | */
76 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock;
77 |
78 | /**
79 | * Set the imageView `image` with an `url`, placeholder.
80 | *
81 | * The download is asynchronous and cached.
82 | *
83 | * @param url The url for the image.
84 | * @param state The state that uses the specified title. The values are described in UIControlState.
85 | * @param placeholder The image to be set initially, until the image request finishes.
86 | * @param completedBlock A block called when operation has been completed. This block has no return value
87 | * and takes the requested UIImage as first parameter. In case of error the image parameter
88 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
89 | * indicating if the image was retrived from the local cache or from the network.
90 | * The fourth parameter is the original image url.
91 | */
92 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
93 |
94 | /**
95 | * Set the imageView `image` with an `url`, placeholder and custom options.
96 | *
97 | * The download is asynchronous and cached.
98 | *
99 | * @param url The url for the image.
100 | * @param state The state that uses the specified title. The values are described in UIControlState.
101 | * @param placeholder The image to be set initially, until the image request finishes.
102 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
103 | * @param completedBlock A block called when operation has been completed. This block has no return value
104 | * and takes the requested UIImage as first parameter. In case of error the image parameter
105 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
106 | * indicating if the image was retrived from the local cache or from the network.
107 | * The fourth parameter is the original image url.
108 | */
109 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
110 |
111 | /**
112 | * Set the backgroundImageView `image` with an `url`.
113 | *
114 | * The download is asynchronous and cached.
115 | *
116 | * @param url The url for the image.
117 | * @param state The state that uses the specified title. The values are described in UIControlState.
118 | */
119 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state;
120 |
121 | /**
122 | * Set the backgroundImageView `image` with an `url` and a placeholder.
123 | *
124 | * The download is asynchronous and cached.
125 | *
126 | * @param url The url for the image.
127 | * @param state The state that uses the specified title. The values are described in UIControlState.
128 | * @param placeholder The image to be set initially, until the image request finishes.
129 | * @see sd_setImageWithURL:placeholderImage:options:
130 | */
131 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder;
132 |
133 | /**
134 | * Set the backgroundImageView `image` with an `url`, placeholder and custom options.
135 | *
136 | * The download is asynchronous and cached.
137 | *
138 | * @param url The url for the image.
139 | * @param state The state that uses the specified title. The values are described in UIControlState.
140 | * @param placeholder The image to be set initially, until the image request finishes.
141 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
142 | */
143 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
144 |
145 | /**
146 | * Set the backgroundImageView `image` with an `url`.
147 | *
148 | * The download is asynchronous and cached.
149 | *
150 | * @param url The url for the image.
151 | * @param state The state that uses the specified title. The values are described in UIControlState.
152 | * @param completedBlock A block called when operation has been completed. This block has no return value
153 | * and takes the requested UIImage as first parameter. In case of error the image parameter
154 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
155 | * indicating if the image was retrived from the local cache or from the network.
156 | * The fourth parameter is the original image url.
157 | */
158 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock;
159 |
160 | /**
161 | * Set the backgroundImageView `image` with an `url`, placeholder.
162 | *
163 | * The download is asynchronous and cached.
164 | *
165 | * @param url The url for the image.
166 | * @param state The state that uses the specified title. The values are described in UIControlState.
167 | * @param placeholder The image to be set initially, until the image request finishes.
168 | * @param completedBlock A block called when operation has been completed. This block has no return value
169 | * and takes the requested UIImage as first parameter. In case of error the image parameter
170 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
171 | * indicating if the image was retrived from the local cache or from the network.
172 | * The fourth parameter is the original image url.
173 | */
174 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
175 |
176 | /**
177 | * Set the backgroundImageView `image` with an `url`, placeholder and custom options.
178 | *
179 | * The download is asynchronous and cached.
180 | *
181 | * @param url The url for the image.
182 | * @param placeholder The image to be set initially, until the image request finishes.
183 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
184 | * @param completedBlock A block called when operation has been completed. This block has no return value
185 | * and takes the requested UIImage as first parameter. In case of error the image parameter
186 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
187 | * indicating if the image was retrived from the local cache or from the network.
188 | * The fourth parameter is the original image url.
189 | */
190 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
191 |
192 | /**
193 | * Cancel the current image download
194 | */
195 | - (void)sd_cancelImageLoadForState:(UIControlState)state;
196 |
197 | /**
198 | * Cancel the current backgroundImage download
199 | */
200 | - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state;
201 |
202 | @end
203 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/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 | _executionOrder = SDWebImageDownloaderFIFOExecutionOrder;
69 | _downloadQueue = [NSOperationQueue new];
70 | _downloadQueue.maxConcurrentOperationCount = 6;
71 | _URLCallbacks = [NSMutableDictionary new];
72 | _HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"];
73 | _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
74 | _downloadTimeout = 15.0;
75 | }
76 | return self;
77 | }
78 |
79 | - (void)dealloc {
80 | [self.downloadQueue cancelAllOperations];
81 | SDDispatchQueueRelease(_barrierQueue);
82 | }
83 |
84 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field {
85 | if (value) {
86 | self.HTTPHeaders[field] = value;
87 | }
88 | else {
89 | [self.HTTPHeaders removeObjectForKey:field];
90 | }
91 | }
92 |
93 | - (NSString *)valueForHTTPHeaderField:(NSString *)field {
94 | return self.HTTPHeaders[field];
95 | }
96 |
97 | - (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads {
98 | _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads;
99 | }
100 |
101 | - (NSUInteger)currentDownloadCount {
102 | return _downloadQueue.operationCount;
103 | }
104 |
105 | - (NSInteger)maxConcurrentDownloads {
106 | return _downloadQueue.maxConcurrentOperationCount;
107 | }
108 |
109 | - (void)setOperationClass:(Class)operationClass {
110 | _operationClass = operationClass ?: [SDWebImageDownloaderOperation class];
111 | }
112 |
113 | - (id )downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock {
114 | __block SDWebImageDownloaderOperation *operation;
115 | __weak SDWebImageDownloader *wself = self;
116 |
117 | [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{
118 | NSTimeInterval timeoutInterval = wself.downloadTimeout;
119 | if (timeoutInterval == 0.0) {
120 | timeoutInterval = 15.0;
121 | }
122 |
123 | // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise
124 | NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval];
125 | request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies);
126 | request.HTTPShouldUsePipelining = YES;
127 | if (wself.headersFilter) {
128 | request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]);
129 | }
130 | else {
131 | request.allHTTPHeaderFields = wself.HTTPHeaders;
132 | }
133 | operation = [[wself.operationClass alloc] initWithRequest:request
134 | options:options
135 | progress:^(NSInteger receivedSize, NSInteger expectedSize) {
136 | SDWebImageDownloader *sself = wself;
137 | if (!sself) return;
138 | NSArray *callbacksForURL = [sself callbacksForURL:url];
139 | for (NSDictionary *callbacks in callbacksForURL) {
140 | SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey];
141 | if (callback) callback(receivedSize, expectedSize);
142 | }
143 | }
144 | completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
145 | SDWebImageDownloader *sself = wself;
146 | if (!sself) return;
147 | NSArray *callbacksForURL = [sself callbacksForURL:url];
148 | if (finished) {
149 | [sself removeCallbacksForURL:url];
150 | }
151 | for (NSDictionary *callbacks in callbacksForURL) {
152 | SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey];
153 | if (callback) callback(image, data, error, finished);
154 | }
155 | }
156 | cancelled:^{
157 | SDWebImageDownloader *sself = wself;
158 | if (!sself) return;
159 | [sself removeCallbacksForURL:url];
160 | }];
161 |
162 | if (wself.username && wself.password) {
163 | operation.credential = [NSURLCredential credentialWithUser:wself.username password:wself.password persistence:NSURLCredentialPersistenceForSession];
164 | }
165 |
166 | if (options & SDWebImageDownloaderHighPriority) {
167 | operation.queuePriority = NSOperationQueuePriorityHigh;
168 | } else if (options & SDWebImageDownloaderLowPriority) {
169 | operation.queuePriority = NSOperationQueuePriorityLow;
170 | }
171 |
172 | [wself.downloadQueue addOperation:operation];
173 | if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
174 | // Emulate LIFO execution order by systematically adding new operations as last operation's dependency
175 | [wself.lastAddedOperation addDependency:operation];
176 | wself.lastAddedOperation = operation;
177 | }
178 | }];
179 |
180 | return operation;
181 | }
182 |
183 | - (void)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock andCompletedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(NSURL *)url createCallback:(SDWebImageNoParamsBlock)createCallback {
184 | // 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.
185 | if (url == nil) {
186 | if (completedBlock != nil) {
187 | completedBlock(nil, nil, nil, NO);
188 | }
189 | return;
190 | }
191 |
192 | dispatch_barrier_sync(self.barrierQueue, ^{
193 | BOOL first = NO;
194 | if (!self.URLCallbacks[url]) {
195 | self.URLCallbacks[url] = [NSMutableArray new];
196 | first = YES;
197 | }
198 |
199 | // Handle single download of simultaneous download request for the same URL
200 | NSMutableArray *callbacksForURL = self.URLCallbacks[url];
201 | NSMutableDictionary *callbacks = [NSMutableDictionary new];
202 | if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy];
203 | if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy];
204 | [callbacksForURL addObject:callbacks];
205 | self.URLCallbacks[url] = callbacksForURL;
206 |
207 | if (first) {
208 | createCallback();
209 | }
210 | });
211 | }
212 |
213 | - (NSArray *)callbacksForURL:(NSURL *)url {
214 | __block NSArray *callbacksForURL;
215 | dispatch_sync(self.barrierQueue, ^{
216 | callbacksForURL = self.URLCallbacks[url];
217 | });
218 | return [callbacksForURL copy];
219 | }
220 |
221 | - (void)removeCallbacksForURL:(NSURL *)url {
222 | dispatch_barrier_async(self.barrierQueue, ^{
223 | [self.URLCallbacks removeObjectForKey:url];
224 | });
225 | }
226 |
227 | - (void)setSuspended:(BOOL)suspended {
228 | [self.downloadQueue setSuspended:suspended];
229 | }
230 |
231 | @end
232 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/VVeboTableView.m:
--------------------------------------------------------------------------------
1 | //
2 | // VVeboTableView.m
3 | // VVeboTableViewDemo
4 | //
5 | // Created by Johnil on 15/5/25.
6 | // Copyright (c) 2015年 Johnil. All rights reserved.
7 | //
8 |
9 | #import "VVeboTableView.h"
10 | #import "NSString+Additions.h"
11 | #import "UIScreen+Additions.h"
12 | #import "VVeboTableViewCell.h"
13 | #import "UIView+Additions.h"
14 | @interface VVeboTableView()
15 |
16 | @end
17 |
18 | @implementation VVeboTableView{
19 | NSMutableArray *datas;
20 | NSMutableArray *needLoadArr;
21 | BOOL scrollToToping;
22 | }
23 |
24 | - (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{
25 | self = [super initWithFrame:frame style:style];
26 | if (self) {
27 | self.separatorStyle = UITableViewCellSeparatorStyleNone;
28 | self.dataSource = self;
29 | self.delegate = self;
30 | datas = [[NSMutableArray alloc] init];
31 | needLoadArr = [[NSMutableArray alloc] init];
32 |
33 | [self loadData];
34 | [self reloadData];
35 | }
36 | return self;
37 | }
38 |
39 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
40 | return datas.count;
41 | }
42 |
43 | - (NSInteger)numberOfSections{
44 | return 1;
45 | }
46 |
47 | - (void)drawCell:(VVeboTableViewCell *)cell withIndexPath:(NSIndexPath *)indexPath{
48 | NSDictionary *data = [datas objectAtIndex:indexPath.row];
49 | cell.selectionStyle = UITableViewCellSelectionStyleNone;
50 | [cell clear];
51 | cell.data = data;
52 | if (needLoadArr.count>0&&[needLoadArr indexOfObject:indexPath]==NSNotFound) {
53 | [cell clear];
54 | return;
55 | }
56 | if (scrollToToping) {
57 | return;
58 | }
59 | [cell draw];
60 | }
61 |
62 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
63 | VVeboTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
64 | if (cell==nil) {
65 | cell = [[VVeboTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
66 | reuseIdentifier:@"cell"];
67 | }
68 | [self drawCell:cell withIndexPath:indexPath];
69 | return cell;
70 | }
71 |
72 | - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
73 | NSDictionary *dict = datas[indexPath.row];
74 | float height = [dict[@"frame"] CGRectValue].size.height;
75 | return height;
76 | }
77 |
78 | - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
79 | [needLoadArr removeAllObjects];
80 | }
81 |
82 | //按需加载 - 如果目标行与当前行相差超过指定行数,只在目标滚动范围的前后指定3行加载。
83 | - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
84 | NSIndexPath *ip = [self indexPathForRowAtPoint:CGPointMake(0, targetContentOffset->y)];
85 | NSIndexPath *cip = [[self indexPathsForVisibleRows] firstObject];
86 | NSInteger skipCount = 8;
87 | if (labs(cip.row-ip.row)>skipCount) {
88 | NSArray *temp = [self indexPathsForRowsInRect:CGRectMake(0, targetContentOffset->y, self.width, self.height)];
89 | NSMutableArray *arr = [NSMutableArray arrayWithArray:temp];
90 | if (velocity.y<0) {
91 | NSIndexPath *indexPath = [temp lastObject];
92 | if (indexPath.row+33) {
100 | [arr addObject:[NSIndexPath indexPathForRow:indexPath.row-3 inSection:0]];
101 | [arr addObject:[NSIndexPath indexPathForRow:indexPath.row-2 inSection:0]];
102 | [arr addObject:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:0]];
103 | }
104 | }
105 | [needLoadArr addObjectsFromArray:arr];
106 | }
107 | }
108 |
109 | - (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView{
110 | scrollToToping = YES;
111 | return YES;
112 | }
113 |
114 | - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
115 | scrollToToping = NO;
116 | [self loadContent];
117 | }
118 |
119 | - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView{
120 | scrollToToping = NO;
121 | [self loadContent];
122 | }
123 |
124 | //用户触摸时第一时间加载内容
125 | - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
126 | if (!scrollToToping) {
127 | [needLoadArr removeAllObjects];
128 | [self loadContent];
129 | }
130 | return [super hitTest:point withEvent:event];
131 | }
132 |
133 | - (void)loadContent{
134 | if (scrollToToping) {
135 | return;
136 | }
137 | if (self.indexPathsForVisibleRows.count<=0) {
138 | return;
139 | }
140 | if (self.visibleCells&&self.visibleCells.count>0) {
141 | for (id temp in [self.visibleCells copy]) {
142 | VVeboTableViewCell *cell = (VVeboTableViewCell *)temp;
143 | [cell draw];
144 | }
145 | }
146 | }
147 |
148 | //读取信息
149 | - (void)loadData{
150 | NSArray *temp = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];
151 | for (NSDictionary *dict in temp) {
152 | NSDictionary *user = dict[@"user"];
153 | NSMutableDictionary *data = [NSMutableDictionary dictionary];
154 | data[@"avatarUrl"] = user[@"avatar_large"];
155 | data[@"name"] = user[@"screen_name"];
156 | NSString *from = [dict valueForKey:@"source"];
157 | if (from.length>6) {
158 | NSInteger start = [from indexOf:@"\">"]+2;
159 | NSInteger end = [from indexOf:@""];
160 | from = [from substringFromIndex:start toIndex:end];
161 | } else {
162 | from = @"未知";
163 | }
164 | data[@"time"] = @"2015-05-25";
165 | data[@"from"] = from;
166 | [self setCommentsFrom:dict toData:data];
167 | [self setRepostsFrom:dict toData:data];
168 | data[@"text"] = dict[@"text"];
169 |
170 | NSDictionary *retweet = [dict valueForKey:@"retweeted_status"];
171 | if (retweet) {
172 | NSMutableDictionary *subData = [NSMutableDictionary dictionary];
173 | NSDictionary *user = retweet[@"user"];
174 | subData[@"avatarUrl"] = user[@"avatar_large"];
175 | subData[@"name"] = user[@"screen_name"];
176 | subData[@"text"] = [NSString stringWithFormat:@"@%@: %@", subData[@"name"], retweet[@"text"]];
177 | [self setPicUrlsFrom:retweet toData:subData];
178 |
179 | {
180 | float width = [UIScreen screenWidth]-SIZE_GAP_LEFT*2;
181 | CGSize size = [subData[@"text"] sizeWithConstrainedToWidth:width fromFont:FontWithSize(SIZE_FONT_SUBCONTENT) lineSpace:5];
182 | NSInteger sizeHeight = (size.height+.5);
183 | subData[@"textRect"] = [NSValue valueWithCGRect:CGRectMake(SIZE_GAP_LEFT, SIZE_GAP_BIG, width, sizeHeight)];
184 | sizeHeight += SIZE_GAP_BIG;
185 | if (subData[@"pic_urls"] && [subData[@"pic_urls"] count]>0) {
186 | sizeHeight += (SIZE_GAP_IMG+SIZE_IMAGE+SIZE_GAP_IMG);
187 | }
188 | sizeHeight += SIZE_GAP_BIG;
189 | subData[@"frame"] = [NSValue valueWithCGRect:CGRectMake(0, 0, [UIScreen screenWidth], sizeHeight)];
190 | }
191 | data[@"subData"] = subData;
192 | } else {
193 | [self setPicUrlsFrom:dict toData:data];
194 | }
195 |
196 | {
197 | float width = [UIScreen screenWidth]-SIZE_GAP_LEFT*2;
198 | CGSize size = [data[@"text"] sizeWithConstrainedToWidth:width fromFont:FontWithSize(SIZE_FONT_CONTENT) lineSpace:5];
199 | NSInteger sizeHeight = (size.height+.5);
200 | data[@"textRect"] = [NSValue valueWithCGRect:CGRectMake(SIZE_GAP_LEFT, SIZE_GAP_TOP+SIZE_AVATAR+SIZE_GAP_BIG, width, sizeHeight)];
201 | sizeHeight += SIZE_GAP_TOP+SIZE_AVATAR+SIZE_GAP_BIG;
202 | if (data[@"pic_urls"] && [data[@"pic_urls"] count]>0) {
203 | sizeHeight += (SIZE_GAP_IMG+SIZE_IMAGE+SIZE_GAP_IMG);
204 | }
205 |
206 | NSMutableDictionary *subData = [data valueForKey:@"subData"];
207 | if (subData) {
208 | sizeHeight += SIZE_GAP_BIG;
209 | CGRect frame = [subData[@"frame"] CGRectValue];
210 | CGRect textRect = [subData[@"textRect"] CGRectValue];
211 | frame.origin.y = sizeHeight;
212 | subData[@"frame"] = [NSValue valueWithCGRect:frame];
213 | textRect.origin.y = frame.origin.y+SIZE_GAP_BIG;
214 | subData[@"textRect"] = [NSValue valueWithCGRect:textRect];
215 | sizeHeight += frame.size.height;
216 | data[@"subData"] = subData;
217 | }
218 |
219 | sizeHeight += 30;
220 | data[@"frame"] = [NSValue valueWithCGRect:CGRectMake(0, 0, [UIScreen screenWidth], sizeHeight)];
221 | }
222 |
223 | [datas addObject:data];
224 | }
225 | }
226 |
227 | - (void)setCommentsFrom:(NSDictionary *)dict toData:(NSMutableDictionary *)data{
228 | NSInteger comments = [dict[@"reposts_count"] integerValue];
229 | if (comments>=10000) {
230 | data[@"reposts"] = [NSString stringWithFormat:@" %.1fw", comments/10000.0];
231 | } else {
232 | if (comments>0) {
233 | data[@"reposts"] = [NSString stringWithFormat:@" %ld", (long)comments];
234 | } else {
235 | data[@"reposts"] = @"";
236 | }
237 | }
238 | }
239 |
240 | - (void)setRepostsFrom:(NSDictionary *)dict toData:(NSMutableDictionary *)data{
241 | NSInteger comments = [dict[@"comments_count"] integerValue];
242 | if (comments>=10000) {
243 | data[@"comments"] = [NSString stringWithFormat:@" %.1fw", comments/10000.0];
244 | } else {
245 | if (comments>0) {
246 | data[@"comments"] = [NSString stringWithFormat:@" %ld", (long)comments];
247 | } else {
248 | data[@"comments"] = @"";
249 | }
250 | }
251 | }
252 |
253 | - (void)setPicUrlsFrom:(NSDictionary *)dict toData:(NSMutableDictionary *)data{
254 | NSArray *pic_urls = [dict valueForKey:@"pic_urls"];
255 | NSString *url = [dict valueForKey:@"thumbnail_pic"];
256 | NSArray *pic_ids = [dict valueForKey:@"pic_ids"];
257 | if (pic_ids && pic_ids.count>1) {
258 | NSString *typeStr = @"jpg";
259 | if (pic_ids.count>0||url.length>0) {
260 | typeStr = [url substringFromIndex:url.length-3];
261 | }
262 | NSMutableArray *temp = [NSMutableArray array];
263 | for (NSString *pic_url in pic_ids) {
264 | [temp addObject:@{@"thumbnail_pic": [NSString stringWithFormat:@"http://ww2.sinaimg.cn/thumbnail/%@.%@", pic_url, typeStr]}];
265 | }
266 | data[@"pic_urls"] = temp;
267 | } else {
268 | data[@"pic_urls"] = pic_urls;
269 | }
270 | }
271 |
272 | - (void)removeFromSuperview{
273 | for (UIView *temp in self.subviews) {
274 | for (VVeboTableViewCell *cell in temp.subviews) {
275 | if ([cell isKindOfClass:[VVeboTableViewCell class]]) {
276 | [cell releaseMemory];
277 | }
278 | }
279 | }
280 | [[NSNotificationCenter defaultCenter] removeObserver:self];
281 | [datas removeAllObjects];
282 | datas = nil;
283 | [self reloadData];
284 | self.delegate = nil;
285 | [needLoadArr removeAllObjects];
286 | needLoadArr = nil;
287 | [super removeFromSuperview];
288 | }
289 |
290 | @end
291 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/view/VVeboTableViewCell.m:
--------------------------------------------------------------------------------
1 | //
2 | // VVeboTableViewCell.m
3 | // VVeboTableViewDemo
4 | //
5 | // Created by Johnil on 15/5/25.
6 | // Copyright (c) 2015年 Johnil. All rights reserved.
7 | //
8 |
9 | #import "VVeboTableViewCell.h"
10 | #import "UIView+Additions.h"
11 | #import "UIScreen+Additions.h"
12 | #import "NSString+Additions.h"
13 | #import "VVeboLabel.h"
14 | #import "UIImageView+WebCache.h"
15 | #import "UIButton+WebCache.h"
16 |
17 | @implementation VVeboTableViewCell {
18 | UIImageView *postBGView;
19 | UIButton *avatarView;
20 | UIImageView *cornerImage;
21 | UIView *topLine;
22 | VVeboLabel *label;
23 | VVeboLabel *detailLabel;
24 | UIScrollView *mulitPhotoScrollView;
25 | BOOL drawed;
26 | NSInteger drawColorFlag;
27 | CGRect commentsRect;
28 | CGRect repostsRect;
29 | }
30 |
31 | - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
32 | self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
33 | if (self) {
34 | self.clipsToBounds = YES;
35 | postBGView = [[UIImageView alloc] initWithFrame:CGRectZero];
36 | [self.contentView insertSubview:postBGView atIndex:0];
37 |
38 | avatarView = [UIButton buttonWithType:UIButtonTypeCustom];//[[VVeboAvatarView alloc] initWithFrame:avatarRect];
39 | avatarView.frame = CGRectMake(SIZE_GAP_LEFT, SIZE_GAP_TOP, SIZE_AVATAR, SIZE_AVATAR);
40 | avatarView.backgroundColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1];
41 | avatarView.hidden = NO;
42 | avatarView.tag = NSIntegerMax;
43 | avatarView.clipsToBounds = YES;
44 | [self.contentView addSubview:avatarView];
45 |
46 | cornerImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SIZE_AVATAR+5, SIZE_AVATAR+5)];
47 | cornerImage.center = avatarView.center;
48 | cornerImage.image = [UIImage imageNamed:@"corner_circle@2x.png"];
49 | cornerImage.tag = NSIntegerMax;
50 | [self.contentView addSubview:cornerImage];
51 |
52 | topLine = [[UIView alloc] initWithFrame:CGRectMake(0, self.height-.5, [UIScreen screenWidth], .5)];
53 | topLine.backgroundColor = [UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1];
54 | topLine.tag = NSIntegerMax;
55 | [self.contentView addSubview:topLine];
56 |
57 | self.backgroundColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1];
58 |
59 | [self addLabel];
60 |
61 | mulitPhotoScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
62 | mulitPhotoScrollView.scrollsToTop = NO;
63 | mulitPhotoScrollView.showsHorizontalScrollIndicator = NO;
64 | mulitPhotoScrollView.showsVerticalScrollIndicator = NO;
65 | mulitPhotoScrollView.tag = NSIntegerMax;
66 | mulitPhotoScrollView.hidden = YES;
67 | [self.contentView addSubview:mulitPhotoScrollView];
68 | int h2 = SIZE_GAP_IMG+SIZE_IMAGE;
69 | for (NSInteger i=0; i<9; i++) {
70 | int g = SIZE_GAP_IMG;
71 | int width = SIZE_IMAGE;
72 | float x = SIZE_GAP_LEFT+(g+width)*(i%3);
73 | float y = i/3*h2;
74 | UIImageView *thumb1 = [[UIImageView alloc] initWithFrame:CGRectMake(x, y+2, SIZE_IMAGE, SIZE_IMAGE)];
75 | thumb1.tag = i+1;
76 | [mulitPhotoScrollView addSubview:thumb1];
77 | }
78 | }
79 | return self;
80 | }
81 |
82 | - (void)setFrame:(CGRect)frame{
83 | [super setFrame:frame];
84 | [self.contentView bringSubviewToFront:topLine];
85 | topLine.y = self.height-.5;
86 | }
87 |
88 | - (void)setData:(NSDictionary *)data{
89 | _data = data;
90 | [avatarView setBackgroundImage:nil forState:UIControlStateNormal];
91 | if ([data valueForKey:@"avatarUrl"]) {
92 | NSURL *url = [NSURL URLWithString:[data valueForKey:@"avatarUrl"]];
93 | [avatarView sd_setBackgroundImageWithURL:url forState:UIControlStateNormal placeholderImage:nil options:SDWebImageLowPriority];
94 | }
95 | }
96 |
97 | - (void)addLabel{
98 | if (label) {
99 | [label removeFromSuperview];
100 | label = nil;
101 | }
102 | if (detailLabel) {
103 | detailLabel = nil;
104 | }
105 | label = [[VVeboLabel alloc] initWithFrame:[_data[@"textRect"] CGRectValue]];
106 | label.textColor = [UIColor colorWithRed:50/255.0 green:50/255.0 blue:50/255.0 alpha:1];
107 | label.backgroundColor = self.backgroundColor;
108 | [self.contentView addSubview:label];
109 |
110 | detailLabel = [[VVeboLabel alloc] initWithFrame:[_data[@"subTextRect"] CGRectValue]];
111 | detailLabel.font = FontWithSize(SIZE_FONT_SUBCONTENT);
112 | detailLabel.textColor = [UIColor colorWithRed:50/255.0 green:50/255.0 blue:50/255.0 alpha:1];;
113 | detailLabel.backgroundColor = [UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1];
114 | [self.contentView addSubview:detailLabel];
115 | }
116 |
117 | //将主要内容绘制到图片上
118 | - (void)draw{
119 | if (drawed) {
120 | return;
121 | }
122 | NSInteger flag = drawColorFlag;
123 | drawed = YES;
124 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
125 | CGRect rect = [_data[@"frame"] CGRectValue];
126 | UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0);
127 | CGContextRef context = UIGraphicsGetCurrentContext();
128 | [[UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1] set];
129 | CGContextFillRect(context, rect);
130 | if ([_data valueForKey:@"subData"]) {
131 | [[UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1] set];
132 | CGRect subFrame = [_data[@"subData"][@"frame"] CGRectValue];
133 | CGContextFillRect(context, subFrame);
134 | [[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1] set];
135 | CGContextFillRect(context, CGRectMake(0, subFrame.origin.y, rect.size.width, .5));
136 | }
137 |
138 | {
139 | float leftX = SIZE_GAP_LEFT+SIZE_AVATAR+SIZE_GAP_BIG;
140 | float x = leftX;
141 | float y = (SIZE_AVATAR-(SIZE_FONT_NAME+SIZE_FONT_SUBTITLE+6))/2-2+SIZE_GAP_TOP+SIZE_GAP_SMALL-5;
142 | [_data[@"name"] drawInContext:context withPosition:CGPointMake(x, y) andFont:FontWithSize(SIZE_FONT_NAME)
143 | andTextColor:[UIColor colorWithRed:106/255.0 green:140/255.0 blue:181/255.0 alpha:1]
144 | andHeight:rect.size.height];
145 | y += SIZE_FONT_NAME+5;
146 | float fromX = leftX;
147 | float size = [UIScreen screenWidth]-leftX;
148 | NSString *from = [NSString stringWithFormat:@"%@ %@", _data[@"time"], _data[@"from"]];
149 | [from drawInContext:context withPosition:CGPointMake(fromX, y) andFont:FontWithSize(SIZE_FONT_SUBTITLE)
150 | andTextColor:[UIColor colorWithRed:178/255.0 green:178/255.0 blue:178/255.0 alpha:1]
151 | andHeight:rect.size.height andWidth:size];
152 | }
153 |
154 | {
155 | CGRect countRect = CGRectMake(0, rect.size.height-30, [UIScreen screenWidth], 30);
156 | [[UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1] set];
157 | CGContextFillRect(context, countRect);
158 | float alpha = 1;
159 |
160 | float x = [UIScreen screenWidth]-SIZE_GAP_LEFT-10;
161 | NSString *comments = _data[@"comments"];
162 | if (comments) {
163 | CGSize size = [comments sizeWithConstrainedToSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) fromFont:FontWithSize(SIZE_FONT_SUBTITLE) lineSpace:5];
164 |
165 | x -= size.width;
166 | [comments drawInContext:context withPosition:CGPointMake(x, 8+countRect.origin.y)
167 | andFont:FontWithSize(12)
168 | andTextColor:[UIColor colorWithRed:178/255.0 green:178/255.0 blue:178/255.0 alpha:1]
169 | andHeight:rect.size.height];
170 | [[UIImage imageNamed:@"t_comments.png"] drawInRect:CGRectMake(x-5, 10.5+countRect.origin.y, 10, 9) blendMode:kCGBlendModeNormal alpha:alpha];
171 | commentsRect = CGRectMake(x-5, self.height-50, [UIScreen screenWidth]-x+5, 50);
172 | x -= 20;
173 | }
174 |
175 | NSString *reposts = _data[@"reposts"];
176 | if (reposts) {
177 | CGSize size = [reposts sizeWithConstrainedToSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) fromFont:FontWithSize(SIZE_FONT_SUBTITLE) lineSpace:5];
178 |
179 | x -= MAX(size.width, 5)+SIZE_GAP_BIG;
180 | [reposts drawInContext:context withPosition:CGPointMake(x, 8+countRect.origin.y)
181 | andFont:FontWithSize(12)
182 | andTextColor:[UIColor colorWithRed:178/255.0 green:178/255.0 blue:178/255.0 alpha:1]
183 | andHeight:rect.size.height];
184 |
185 | [[UIImage imageNamed:@"t_repost.png"] drawInRect:CGRectMake(x-5, 11+countRect.origin.y, 10, 9) blendMode:kCGBlendModeNormal alpha:alpha];
186 | repostsRect = CGRectMake(x-5, self.height-50, commentsRect.origin.x-x, 50);
187 | x -= 20;
188 | }
189 |
190 | [@"•••" drawInContext:context
191 | withPosition:CGPointMake(SIZE_GAP_LEFT, 8+countRect.origin.y)
192 | andFont:FontWithSize(11)
193 | andTextColor:[UIColor colorWithRed:178/255.0 green:178/255.0 blue:178/255.0 alpha:.5]
194 | andHeight:rect.size.height];
195 |
196 | if ([_data valueForKey:@"subData"]) {
197 | [[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1] set];
198 | CGContextFillRect(context, CGRectMake(0, rect.size.height-30.5, rect.size.width, .5));
199 | }
200 | }
201 |
202 | UIImage *temp = UIGraphicsGetImageFromCurrentImageContext();
203 | UIGraphicsEndImageContext();
204 | dispatch_async(dispatch_get_main_queue(), ^{
205 | if (flag==drawColorFlag) {
206 | postBGView.frame = rect;
207 | postBGView.image = nil;
208 | postBGView.image = temp;
209 | }
210 | });
211 | });
212 | [self drawText];
213 | [self loadThumb];
214 | }
215 |
216 | //将文本内容绘制到图片上
217 | - (void)drawText{
218 | if (label==nil||detailLabel==nil) {
219 | [self addLabel];
220 | }
221 | label.frame = [_data[@"textRect"] CGRectValue];
222 | [label setText:_data[@"text"]];
223 | if ([_data valueForKey:@"subData"]) {
224 | detailLabel.frame = [[_data valueForKey:@"subData"][@"textRect"] CGRectValue];
225 | [detailLabel setText:[_data valueForKey:@"subData"][@"text"]];
226 | detailLabel.hidden = NO;
227 | }
228 | }
229 |
230 | - (void)loadThumb{
231 | float y = 0;
232 | NSArray *urls;
233 | if ([_data valueForKey:@"subData"]) {
234 | CGRect subPostRect = [_data[@"subData"][@"textRect"] CGRectValue];
235 | y = subPostRect.origin.y+subPostRect.size.height+SIZE_GAP_BIG;
236 | urls = [_data valueForKey:@"subData"][@"pic_urls"];
237 | } else {
238 | CGRect postRect = [_data[@"textRect"] CGRectValue];
239 | y = postRect.origin.y+postRect.size.height+SIZE_GAP_BIG;
240 | urls = _data[@"pic_urls"];
241 | }
242 | if (urls.count>0) {
243 | mulitPhotoScrollView.hidden = NO;
244 | mulitPhotoScrollView.y = y;
245 | mulitPhotoScrollView.frame = CGRectMake(0, y, [UIScreen screenWidth], SIZE_GAP_IMG+((SIZE_GAP_IMG+SIZE_IMAGE)*(urls.count)));
246 | for (NSInteger i=0; i<9; i++) {
247 | UIImageView *thumbView = (UIImageView *)[mulitPhotoScrollView viewWithTag:i+1];
248 | thumbView.contentMode = UIViewContentModeScaleAspectFill;
249 | thumbView.backgroundColor = [UIColor lightGrayColor];
250 | thumbView.clipsToBounds = YES;
251 | if (i
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 "SDWebImageManager.h"
10 | #import
11 |
12 | @interface SDWebImageCombinedOperation : NSObject
13 |
14 | @property (assign, nonatomic, getter = isCancelled) BOOL cancelled;
15 | @property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock;
16 | @property (strong, nonatomic) NSOperation *cacheOperation;
17 |
18 | @end
19 |
20 | @interface SDWebImageManager ()
21 |
22 | @property (strong, nonatomic, readwrite) SDImageCache *imageCache;
23 | @property (strong, nonatomic, readwrite) SDWebImageDownloader *imageDownloader;
24 | @property (strong, nonatomic) NSMutableArray *failedURLs;
25 | @property (strong, nonatomic) NSMutableArray *runningOperations;
26 |
27 | @end
28 |
29 | @implementation SDWebImageManager
30 |
31 | + (id)sharedManager {
32 | static dispatch_once_t once;
33 | static id instance;
34 | dispatch_once(&once, ^{
35 | instance = [self new];
36 | });
37 | return instance;
38 | }
39 |
40 | - (id)init {
41 | if ((self = [super init])) {
42 | _imageCache = [self createCache];
43 | _imageDownloader = [SDWebImageDownloader sharedDownloader];
44 | _failedURLs = [NSMutableArray new];
45 | _runningOperations = [NSMutableArray new];
46 | }
47 | return self;
48 | }
49 |
50 | - (SDImageCache *)createCache {
51 | return [SDImageCache sharedImageCache];
52 | }
53 |
54 | - (NSString *)cacheKeyForURL:(NSURL *)url {
55 | if (self.cacheKeyFilter) {
56 | return self.cacheKeyFilter(url);
57 | }
58 | else {
59 | return [url absoluteString];
60 | }
61 | }
62 |
63 | - (BOOL)cachedImageExistsForURL:(NSURL *)url {
64 | NSString *key = [self cacheKeyForURL:url];
65 | if ([self.imageCache imageFromMemoryCacheForKey:key] != nil) return YES;
66 | return [self.imageCache diskImageExistsWithKey:key];
67 | }
68 |
69 | - (BOOL)diskImageExistsForURL:(NSURL *)url {
70 | NSString *key = [self cacheKeyForURL:url];
71 | return [self.imageCache diskImageExistsWithKey:key];
72 | }
73 |
74 | - (void)cachedImageExistsForURL:(NSURL *)url
75 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock {
76 | NSString *key = [self cacheKeyForURL:url];
77 |
78 | BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil);
79 |
80 | if (isInMemoryCache) {
81 | // making sure we call the completion block on the main queue
82 | dispatch_async(dispatch_get_main_queue(), ^{
83 | if (completionBlock) {
84 | completionBlock(YES);
85 | }
86 | });
87 | return;
88 | }
89 |
90 | [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
91 | // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
92 | if (completionBlock) {
93 | completionBlock(isInDiskCache);
94 | }
95 | }];
96 | }
97 |
98 | - (void)diskImageExistsForURL:(NSURL *)url
99 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock {
100 | NSString *key = [self cacheKeyForURL:url];
101 |
102 | [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
103 | // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
104 | if (completionBlock) {
105 | completionBlock(isInDiskCache);
106 | }
107 | }];
108 | }
109 |
110 | - (id )downloadImageWithURL:(NSURL *)url
111 | options:(SDWebImageOptions)options
112 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
113 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock {
114 | // Invoking this method without a completedBlock is pointless
115 | NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead");
116 |
117 | // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't
118 | // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString.
119 | if ([url isKindOfClass:NSString.class]) {
120 | url = [NSURL URLWithString:(NSString *)url];
121 | }
122 |
123 | // Prevents app crashing on argument type error like sending NSNull instead of NSURL
124 | if (![url isKindOfClass:NSURL.class]) {
125 | url = nil;
126 | }
127 |
128 | __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
129 | __weak SDWebImageCombinedOperation *weakOperation = operation;
130 |
131 | BOOL isFailedUrl = NO;
132 | @synchronized (self.failedURLs) {
133 | isFailedUrl = [self.failedURLs containsObject:url];
134 | }
135 |
136 | if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
137 | dispatch_main_sync_safe(^{
138 | NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil];
139 | completedBlock(nil, error, SDImageCacheTypeNone, YES, url);
140 | });
141 | return operation;
142 | }
143 |
144 | @synchronized (self.runningOperations) {
145 | [self.runningOperations addObject:operation];
146 | }
147 | NSString *key = [self cacheKeyForURL:url];
148 |
149 | operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) {
150 | if (operation.isCancelled) {
151 | @synchronized (self.runningOperations) {
152 | [self.runningOperations removeObject:operation];
153 | }
154 |
155 | return;
156 | }
157 |
158 | if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
159 | if (image && options & SDWebImageRefreshCached) {
160 | dispatch_main_sync_safe(^{
161 | // If image was found in the cache bug SDWebImageRefreshCached is provided, notify about the cached image
162 | // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server.
163 | completedBlock(image, nil, cacheType, YES, url);
164 | });
165 | }
166 |
167 | // download if no image or requested to refresh anyway, and download allowed by delegate
168 | SDWebImageDownloaderOptions downloaderOptions = 0;
169 | if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority;
170 | if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload;
171 | if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache;
172 | if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground;
173 | if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies;
174 | if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates;
175 | if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority;
176 | if (image && options & SDWebImageRefreshCached) {
177 | // force progressive off if image already cached but forced refreshing
178 | downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload;
179 | // ignore image read from NSURLCache if image if cached but force refreshing
180 | downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse;
181 | }
182 | id subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) {
183 | if (weakOperation.isCancelled) {
184 | // Do nothing if the operation was cancelled
185 | // See #699 for more details
186 | // if we would call the completedBlock, there could be a race condition between this block and another completedBlock for the same object, so if this one is called second, we will overwrite the new data
187 | }
188 | else if (error) {
189 | dispatch_main_sync_safe(^{
190 | if (!weakOperation.isCancelled) {
191 | completedBlock(nil, error, SDImageCacheTypeNone, finished, url);
192 | }
193 | });
194 |
195 | if (error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut) {
196 | @synchronized (self.failedURLs) {
197 | [self.failedURLs addObject:url];
198 | }
199 | }
200 | }
201 | else {
202 | BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly);
203 |
204 | if (options & SDWebImageRefreshCached && image && !downloadedImage) {
205 | // Image refresh hit the NSURLCache cache, do not call the completion block
206 | }
207 | else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) {
208 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
209 | UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];
210 |
211 | if (transformedImage && finished) {
212 | BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage];
213 | [self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:data forKey:key toDisk:cacheOnDisk];
214 | }
215 |
216 | dispatch_main_sync_safe(^{
217 | if (!weakOperation.isCancelled) {
218 | completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished, url);
219 | }
220 | });
221 | });
222 | }
223 | else {
224 | if (downloadedImage && finished) {
225 | [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk];
226 | }
227 |
228 | dispatch_main_sync_safe(^{
229 | if (!weakOperation.isCancelled) {
230 | completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished, url);
231 | }
232 | });
233 | }
234 | }
235 |
236 | if (finished) {
237 | @synchronized (self.runningOperations) {
238 | [self.runningOperations removeObject:operation];
239 | }
240 | }
241 | }];
242 | operation.cancelBlock = ^{
243 | [subOperation cancel];
244 |
245 | @synchronized (self.runningOperations) {
246 | [self.runningOperations removeObject:weakOperation];
247 | }
248 | };
249 | }
250 | else if (image) {
251 | dispatch_main_sync_safe(^{
252 | if (!weakOperation.isCancelled) {
253 | completedBlock(image, nil, cacheType, YES, url);
254 | }
255 | });
256 | @synchronized (self.runningOperations) {
257 | [self.runningOperations removeObject:operation];
258 | }
259 | }
260 | else {
261 | // Image not in cache and download disallowed by delegate
262 | dispatch_main_sync_safe(^{
263 | if (!weakOperation.isCancelled) {
264 | completedBlock(nil, nil, SDImageCacheTypeNone, YES, url);
265 | }
266 | });
267 | @synchronized (self.runningOperations) {
268 | [self.runningOperations removeObject:operation];
269 | }
270 | }
271 | }];
272 |
273 | return operation;
274 | }
275 |
276 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url {
277 | if (image && url) {
278 | NSString *key = [self cacheKeyForURL:url];
279 | [self.imageCache storeImage:image forKey:key toDisk:YES];
280 | }
281 | }
282 |
283 | - (void)cancelAll {
284 | @synchronized (self.runningOperations) {
285 | NSArray *copiedOperations = [self.runningOperations copy];
286 | [copiedOperations makeObjectsPerformSelector:@selector(cancel)];
287 | [self.runningOperations removeObjectsInArray:copiedOperations];
288 | }
289 | }
290 |
291 | - (BOOL)isRunning {
292 | return self.runningOperations.count > 0;
293 | }
294 |
295 | @end
296 |
297 |
298 | @implementation SDWebImageCombinedOperation
299 |
300 | - (void)setCancelBlock:(SDWebImageNoParamsBlock)cancelBlock {
301 | // check if the operation is already cancelled, then we just call the cancelBlock
302 | if (self.isCancelled) {
303 | if (cancelBlock) {
304 | cancelBlock();
305 | }
306 | _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes
307 | } else {
308 | _cancelBlock = [cancelBlock copy];
309 | }
310 | }
311 |
312 | - (void)cancel {
313 | self.cancelled = YES;
314 | if (self.cacheOperation) {
315 | [self.cacheOperation cancel];
316 | self.cacheOperation = nil;
317 | }
318 | if (self.cancelBlock) {
319 | self.cancelBlock();
320 |
321 | // TODO: this is a temporary fix to #809.
322 | // Until we can figure the exact cause of the crash, going with the ivar instead of the setter
323 | // self.cancelBlock = nil;
324 | _cancelBlock = nil;
325 | }
326 | }
327 |
328 | @end
329 |
--------------------------------------------------------------------------------
/VVeboTableViewDemo/UIView+Additions.m:
--------------------------------------------------------------------------------
1 | //
2 | // UIView+Additions.m
3 | // Additions
4 | //
5 | // Created by Johnil on 13-6-7.
6 | // Copyright (c) 2013年 Johnil. All rights reserved.
7 | //
8 |
9 | #import "UIView+Additions.h"
10 | #import
11 | #import
12 |
13 | @implementation UIView (Additions)
14 |
15 | - (float)boundsWidth{
16 | return self.bounds.size.width;
17 | }
18 |
19 | - (float)boundsHeight{
20 | return self.bounds.size.width;
21 | }
22 |
23 | - (void)setBoundsWidth:(float)w{
24 | CGRect frame = self.bounds;
25 | frame.size.width = w;
26 | self.bounds = frame;
27 | }
28 |
29 | - (void)setBoundsHeight:(float)h{
30 | CGRect frame = self.bounds;
31 | frame.size.height = h;
32 | self.bounds = frame;
33 | }
34 |
35 | - (float)x{
36 | return self.frame.origin.x;
37 | }
38 |
39 | - (float)y{
40 | return self.frame.origin.y;
41 | }
42 |
43 | - (float)width{
44 | return self.frame.size.width;
45 | }
46 |
47 | - (float)height{
48 | return self.frame.size.height;
49 | }
50 |
51 | - (void)setX:(float)x{
52 | CGRect frame = self.frame;
53 | frame.origin.x = x;
54 | self.frame = frame;
55 | }
56 |
57 | - (void)setY:(float)y{
58 | CGRect frame = self.frame;
59 | frame.origin.y = y;
60 | self.frame = frame;
61 | }
62 |
63 | - (void)setWidth:(float)w{
64 | CGRect frame = self.frame;
65 | frame.size.width = w;
66 | self.frame = frame;
67 | }
68 |
69 | - (void)setHeight:(float)h{
70 | CGRect frame = self.frame;
71 | frame.size.height = h;
72 | self.frame = frame;
73 | }
74 |
75 | //- (void)fadeIn{
76 | // [self fadeInOnComplet:nil];
77 | //}
78 | //
79 | //- (void)fadeOut{
80 | // [self fadeOutOnComplet:nil];
81 | //}
82 | //
83 | //- (void)fadeInOnComplet:(void(^)(BOOL finished))complet{
84 | // self.alpha = 0;
85 | // [UIView animateWithDuration:.18 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
86 | // self.alpha = 1;
87 | // } completion:complet];
88 | //}
89 | //
90 | //- (void)fadeOutOnComplet:(void(^)(BOOL finished))complet{
91 | // [UIView animateWithDuration:.18 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
92 | // self.alpha = 0;
93 | // } completion:complet];
94 | // if ([UIView areAnimationsEnabled]) {
95 | // [UIView setAnimationsEnabled:YES];
96 | // }
97 | //}
98 | //
99 | //- (void)removeAllSubviews{
100 | // for (UIView *temp in self.subviews) {
101 | // [temp removeFromSuperview];
102 | // }
103 | //}
104 | //
105 | //- (void)removeSubviewWithTag:(NSInteger)tag{
106 | // for (UIView *temp in self.subviews) {
107 | // if (temp.tag==tag) {
108 | // [temp removeFromSuperview];
109 | // }
110 | // }
111 | //}
112 | //
113 | //- (void)removeSubviewExceptTag:(NSInteger)tag{
114 | // for (UIView *temp in self.subviews) {
115 | // if (temp.tag!=tag) {
116 | // if ([temp isKindOfClass:[UIImageView class]]) {
117 | // [(UIImageView *)temp setImage:nil];
118 | // }
119 | // [temp removeFromSuperview];
120 | // }
121 | // }
122 | //}
123 | //
124 | //- (void)removeSubviewExceptClass:(Class)class{
125 | // for (UIView *temp in self.subviews) {
126 | // if (![temp isKindOfClass:class]) {
127 | // [temp removeFromSuperview];
128 | // }
129 | // }
130 | //}
131 | //
132 | //- (UIView *)addLine:(UIColor *)color frame:(CGRect)frame{
133 | // UIView *line = [[UIView alloc] initWithFrame:frame];
134 | // line.backgroundColor = color;
135 | // [self addSubview:line];
136 | // return line;
137 | //}
138 | //
139 | //- (UIImage *)toImage{
140 | // return [self toImagewhithAlpha:NO];
141 | //}
142 | //
143 | //- (UIImage *)toRetinaImageRealTime{
144 | // UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, 0);
145 | // [self.layer renderInContext:UIGraphicsGetCurrentContext()];
146 | // UIImage *screenShotimage = UIGraphicsGetImageFromCurrentImageContext();
147 | // UIGraphicsEndImageContext();
148 | // return screenShotimage;
149 | //}
150 | //
151 | //- (UIImage *)toRetinaImage{
152 | // UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, 0);
153 | // [self drawViewHierarchyInRect:self.bounds
154 | // afterScreenUpdates:NO];
155 | // UIImage *screenShotimage = UIGraphicsGetImageFromCurrentImageContext();
156 | // UIGraphicsEndImageContext();
157 | // return screenShotimage;
158 | //}
159 | //
160 | //- (UIImage *)toAlphaRetinaImageRealTime{
161 | // UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
162 | // [self.layer renderInContext:UIGraphicsGetCurrentContext()];
163 | // UIImage *screenShotimage = UIGraphicsGetImageFromCurrentImageContext();
164 | // UIGraphicsEndImageContext();
165 | // return screenShotimage;
166 | //}
167 | //
168 | //- (UIImage *)toAlphaRetinaImage{
169 | // UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
170 | // [self drawViewHierarchyInRect:self.bounds
171 | // afterScreenUpdates:NO];
172 | // UIImage *screenShotimage = UIGraphicsGetImageFromCurrentImageContext();
173 | // UIGraphicsEndImageContext();
174 | // return screenShotimage;
175 | //}
176 | //
177 | //- (UIImage *)toImagewhithAlpha:(BOOL)alpha{
178 | // NSInteger scale = ([UIDevice isiPhone4]||[UIDevice isiPad])?5:2.5;
179 | // CGSize size = CGSizeMake((NSInteger)(self.width/scale), (NSInteger)self.height/scale);
180 | // UIGraphicsBeginImageContextWithOptions(size, !alpha, 1);
181 | // [self drawViewHierarchyInRect:CGRectMake(0, 0, size.width, size.height)
182 | // afterScreenUpdates:NO];
183 | // UIImage *screenShotimage = UIGraphicsGetImageFromCurrentImageContext();
184 | // UIGraphicsEndImageContext();
185 | // return [screenShotimage normalize];
186 | //}
187 | //
188 | //- (UIImage *)toImageWithRect:(CGRect)frame{
189 | // return [self toImageWithRect:frame withAlpha:NO];
190 | //}
191 | //
192 | //- (void)addBorder{
193 | // UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, .5)];
194 | // line.backgroundColor = [VVeboConfigCenter defaultCenter].color_RepostBorder;
195 | // [self addSubview:line];
196 | //
197 | // UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, self.height-.5, self.width, .5)];
198 | // line2.backgroundColor = [VVeboConfigCenter defaultCenter].color_RepostBorder;
199 | // [self addSubview:line2];
200 | //
201 | // UIView *line3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, .5, self.height)];
202 | // line3.backgroundColor = [VVeboConfigCenter defaultCenter].color_RepostBorder;
203 | // [self addSubview:line3];
204 | //
205 | // UIView *line4 = [[UIView alloc] initWithFrame:CGRectMake(self.width-.5, 0, .5, self.height)];
206 | // line4.backgroundColor = [VVeboConfigCenter defaultCenter].color_RepostBorder;
207 | // [self addSubview:line4];
208 | //}
209 | //
210 | //- (UIImage *)toImageWithRect:(CGRect)frame withAlpha:(BOOL)alpha{
211 | // UIGraphicsBeginImageContextWithOptions(frame.size, !alpha, 1);//这里通过设置scale为1来截取{[UIScreen screenWidth], 49}大小的图,而不是在retina下截取2x大小的图
212 | // CGContextRef context = UIGraphicsGetCurrentContext();
213 | // CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-frame.origin.x, -frame.origin.y));
214 | // [self.layer renderInContext:context];
215 | // UIImage *screenShot1 = UIGraphicsGetImageFromCurrentImageContext();
216 | // UIGraphicsEndImageContext();
217 | // return screenShot1;
218 | //}
219 | //
220 | //- (UIImage *)visbleToImage{
221 | // UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
222 | // CGContextRef context = UIGraphicsGetCurrentContext();
223 | // if ([self isKindOfClass:[UIScrollView class]]) {
224 | // CGPoint offset=[(UIScrollView *)self contentOffset];
225 | // CGContextTranslateCTM(context, -offset.x, -offset.y);
226 | // }
227 | //// [self.layer renderInContext:context];
228 | // [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
229 | // UIImage *visibleScrollViewImage = UIGraphicsGetImageFromCurrentImageContext();
230 | // UIGraphicsEndImageContext();
231 | // return visibleScrollViewImage;
232 | //}
233 | //
234 | //- (void)addWhiteViewWithAlpha:(float)alpha{
235 | // UIView *white = [[UIView alloc] initWithFrame:CGRectChangeOrigin(self.frame, CGPointZero)];
236 | // white.backgroundColor = [UIColor whiteColor];
237 | // white.alpha = alpha;
238 | // [self addSubview:white];
239 | //}
240 | //
241 | //- (void)addWhiteView{
242 | // [self addWhiteViewWithAlpha:.8];
243 | //}
244 | //
245 | //- (void)addBlackView{
246 | // UIView *black = [[UIView alloc] initWithFrame:CGRectChangeOrigin(self.frame, CGPointZero)];
247 | // black.backgroundColor = [UIColor blackColor];
248 | // black.alpha = .85;
249 | // [self addSubview:black];
250 | //}
251 | //
252 | //- (void)addShadowWithAlpha:(float)alpha{
253 | // UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 5, self.bounds.size.width, self.bounds.size.height)];
254 | // [self.layer setShadowColor:[UIColor grayColor].CGColor];
255 | // [self.layer setShadowOpacity:alpha];
256 | // [self.layer setShadowRadius:10.0f];
257 | // [self.layer setShadowPath:[path CGPath]];
258 | //}
259 | //
260 | //- (void)addShadow{
261 | // [self addShadowWithAlpha:1];
262 | //}
263 | //
264 | //- (void)addShadowWithColor:(UIColor *)color{
265 | // UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 5, self.bounds.size.width, self.bounds.size.height)];
266 | // [self.layer setShadowColor:color.CGColor];
267 | // [self.layer setShadowOpacity:1];
268 | // [self.layer setShadowRadius:10.0f];
269 | // [self.layer setShadowPath:[path CGPath]];
270 | //}
271 | //
272 | //- (void)removeShadow{
273 | // self.layer.shadowOpacity = 0;
274 | // self.layer.shadowRadius = 0;
275 | //}
276 | //
277 | //- (UIView *)findAndResignFirstResponder{
278 | // if (self.isFirstResponder) {
279 | // return self;
280 | // }
281 | // for (UIView *subView in self.subviews) {
282 | // UIView *temp = [subView findAndResignFirstResponder];
283 | // if (temp!=nil) {
284 | // return temp;
285 | // }
286 | // }
287 | // return nil;
288 | //}
289 | //
290 | //- (void)addCorner{
291 | // UIImageView *cornder = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"corner.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 15, 15, 15)]];
292 | // cornder.contentMode = UIViewContentModeScaleAspectFit;
293 | // cornder.frame = CGRectMake(0, 0, self.width, self.height);
294 | // [self addSubview:cornder];
295 | //}
296 | //
297 | //- (void)shake:(float)range{
298 | // CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.y"];
299 | // animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
300 | // animation.duration = 0.5;
301 | // animation.values = @[ @(-range), @(range), @(-range/2), @(range/2), @(-range/5), @(range/5), @(0) ];
302 | // [self.layer addAnimation:animation forKey:@"shake"];
303 | //}
304 | //
305 | //- (void)shakeRepeat:(float)range{
306 | // CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.y"];
307 | // animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
308 | // animation.duration = 0.6;
309 | // animation.values = @[ @(-range), @(range), @(-range/2), @(range/2), @(-range/5), @(range/5), @(0) ];
310 | // animation.repeatCount = NSIntegerMax;
311 | // [self.layer addAnimation:animation forKey:@"shake"];
312 | //}
313 | //
314 | //- (void)shakeX:(float)range{
315 | // CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
316 | // animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
317 | // animation.duration = 0.6;
318 | // animation.values = @[ @(-range), @(range), @(-range/2), @(range/2), @(-range/5), @(range/5), @(0) ];
319 | // [self.layer addAnimation:animation forKey:@"shake"];
320 | //}
321 | //
322 | //- (void)rasterize{
323 | // self.layer.shouldRasterize = YES;
324 | // self.layer.rasterizationScale = [UIScreen scale];
325 | //}
326 | //
327 | //+ (void)vveboAnimations:(void (^)(void))animations{
328 | // [UIView vveboAnimateWithDuration:.18 delay:0 animations:animations completion:nil];
329 | //}
330 | //
331 | //+ (void)vveboAnimations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion{
332 | // [UIView vveboAnimateWithDuration:.18 delay:0 animations:animations completion:completion];
333 | //}
334 | //
335 | //+ (void)vveboAnimateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations{
336 | // [UIView vveboAnimateWithDuration:duration delay:0 animations:animations completion:nil];
337 | //}
338 | //
339 | //+ (void)vveboAnimateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion{
340 | // [UIView vveboAnimateWithDuration:duration delay:0 animations:animations completion:completion];
341 | //}
342 | //
343 | //+ (void)vveboAnimateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion{
344 | // [UIView vveboAnimateWithDuration:duration delay:delay options:UIViewAnimationOptionCurveLinear animations:animations completion:completion];
345 | //}
346 | //
347 | //+ (void)vveboAnimateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion{
348 | // if (![UIView areAnimationsEnabled]) {
349 | // [UIView setAnimationsEnabled:YES];
350 | // }
351 | // [UIView animateWithDuration:duration delay:delay options:options animations:animations completion:completion];
352 | //}
353 | //
354 | //- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
355 | // if (self.touchBeganBlock) {
356 | // self.touchBeganBlock([touches anyObject], self);
357 | // }
358 | // [super touchesBegan:touches withEvent:event];
359 | //}
360 | //
361 | //- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
362 | // if (self.touchEndBlock) {
363 | // self.touchEndBlock([touches anyObject], self);
364 | // }
365 | // [super touchesEnded:touches withEvent:event];
366 | //}
367 | //
368 | //- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
369 | // if (self.touchMoveBlock) {
370 | // self.touchMoveBlock([touches anyObject], self);
371 | // }
372 | // [super touchesMoved:touches withEvent:event];
373 | //}
374 | //
375 | //- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
376 | // if (self.touchEndBlock) {
377 | // self.touchEndBlock([touches anyObject], self);
378 | // }
379 | // [super touchesCancelled:touches withEvent:event];
380 | //}
381 | //
382 | //- (void)addLine:(CGRect)rect{
383 | // UIColor *color = self.lineColor;
384 | // if (self.lineColor==nil) {
385 | // color = [UIColor grayColor];
386 | // }
387 | // UIView *line = [[UIView alloc] initWithFrame:rect];
388 | // line.backgroundColor = color;
389 | // [self addSubview:line];
390 | //}
391 | //
392 | //- (BOOL)hasActionSheetOrAlert{
393 | // if ([self isKindOfClass:[UIAlertView class]]||[self isKindOfClass:[UIActionSheet class]]) {
394 | // return YES;
395 | // }
396 | // for (UIView *subView in self.subviews) {
397 | // BOOL temp = [subView hasActionSheetOrAlert];
398 | // if (temp) {
399 | // return temp;
400 | // }
401 | // }
402 | // return NO;
403 | //}
404 | //
405 | //- (UIView *)subviewWithTag:(NSInteger)tag{
406 | // for (UIView *temp in self.subviews) {
407 | // if (temp.tag==tag) {
408 | // return temp;
409 | // }
410 | // }
411 | // return nil;
412 | //}
413 |
414 | @end
415 |
--------------------------------------------------------------------------------