第三天任務:
今天主要任務完成我的模塊的搭建。
- 我的頁面的搭建
- 清除緩存功能
- 方法抽取總結
我的頁面的搭建
我們先來看一下我的界面內容
通過上面圖片可以看出,我的界面是一個非常簡單的tableView,上面兩個cell只需要簡單設置圖片,文字和最右邊箭頭就可以了,主要是最下面方塊view的顯示。這里我們有兩種解決方案
一:可以是一個cell,如果最后一個是一個cell,稍微有些麻煩,因為最后一個cell比較特殊,需要與前兩個cell區分,沒有辦法統一設置。
二:可以是一個tablefootView,這種方法比較簡單,我們直接自定義view顯示自己想要顯示的內容,然后添加到tablefootView上面就可以了。
創建自定義view CLMeFooterView。首先分析,CLMeFooterView需要有哪些功能
- 請求數據,本著面向對象,誰的任務誰來負責的基本原則,我們將數據請求寫在CLMeFooterView中
- 布局子控件,CLMeFooterView只管布局子控件和添加點擊事件即可,至于子控件中的內容和字體大小顏色等等,都讓子控件自己去管理,另外CLMeFooterView的寬度是固定的但是需要根據子控件的多少來設置自己的長度。
- 點擊事件的實現,需要根據模型參數的不同,判斷是調到其他界面還是進行http請求
我們通過重寫CLMeFooterView的initWithFrame方法,在initWithFrame方法中請求數據和布局子控件。
代碼中使用AFN來請求數據,使用MJExtension對數據進行對模型的轉換。在請求數據時,可以現在請求成功之后,將服務器返回的數據寫到plist文件中存放到桌面,這樣便于我們對返回數據層次結構的理解和里面數據的查閱
// 寫出plist文件到桌面 便于我們看
// [responseObject writeToFile:@"/Users/yangboxing/Desktop/me.plist" atomically:YES];
查看寫在桌面的plist文件,
通過觀察我們發現square_list中我們只需要用到icon , name ,url,三個屬性就可以了其他的屬性并不用到,也就沒有必要去浪費內存存儲用不到的數據,據此創建CLMeSquare模型,至于數據轉模型MJExtension內部已經幫我們實現。
來看一下請求數據代碼
// 參數
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"a"] = @"square";
params[@"c"] = @"topic";
[[AFHTTPSessionManager manager]GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
// 將字典中square_list對應的數據轉化為模型數組
NSArray *squares = [CLMeSquare mj_objectArrayWithKeyValuesArray:responseObject[@"square_list"]];
[self createSquare:squares];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
CLLog(@"請求失敗");
}];
關于AFN的使用請參考iOS-網絡編程(三)AFNetworking使用
而MJExtension內部通過RunTime來進行字典轉模型,與KVC不同的是,RunTime字典轉模型實現原理是遍歷模型中的所有屬性名,然后去字典查找,也就是以模型為準,模型中有哪些屬性,就去字典中找那些屬性。當服務器返回的數據過多,而我們只使用其中很少一部分時,沒有用的屬性就沒有必要定義成屬性了。
數據請求成功接下來就是子控件的布局,子控件的布局就是很簡單的九宮格布局,需要注意的一點是,我們需要設置footView的高度就等于最后一個子控件的最大Y值,并且在tableView中,cell顯示完畢后,在最低端會多出20的距離。如下圖:
解決的方法非常簡單,當設置完footView的高度之后,拿到tableView重新刷新一下tableView就可以了
// 布局子控件
-(void)createSquare:(NSArray *)squares
{
NSUInteger count = squares.count;
int maxColsCount = 4;
CGFloat buttonW = self.cl_width / 4;
CGFloat buttonH = buttonW;
for (int i = 0; i < count; i ++) {
CLMeSquare *square = squares[i];
CLMeSquareButton *button =[CLMeSquareButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
// 設置button的模型屬性
button.square = square;
// 設置button的frame
button.cl_x = (i % maxColsCount) * buttonW;
button.cl_y = (i / maxColsCount) * buttonH;
button.cl_width = buttonW;
button.cl_height = buttonH;
button.backgroundColor = [UIColor whiteColor];
[self addSubview:button];
}
self.cl_height = self.subviews.lastObject.cl_bottom;
UITableView *tableView = (UITableView *)self.superview;
tableView.tableFooterView = self;
[tableView reloadData]; // 重新刷新數據也會重新計算 contentSize 就不會在最后在增加20了。
}
而子控件的內容由子控件自己來設置,每一個子控件為正方形,可以顯示圖片文字,并且有點擊事件,所以子控件可以使用Button。
創建自定義控件CLMeSquareButton,重寫layoutSubviews來布置button中imageView和titleLabel的位置
-(void)layoutSubviews
{
[super layoutSubviews];
// 修改button 內imageView 和 label的位置
self.imageView.cl_y = self.cl_height * 0.15;
self.imageView.cl_width = self.cl_width * 0.5;
self.imageView.cl_height = self.imageView.cl_width;
self.imageView.cl_centerX = self.cl_width * 0.5;
self.titleLabel.cl_x = 0;
self.titleLabel.cl_y = self.imageView.cl_bottom;
self.titleLabel.cl_width = self.cl_width;
self.titleLabel.cl_height = self.cl_height - self.imageView.cl_bottom;
}
initWithFrame方法中設置button字體大小,顏色,居中,背景圖片等。
-(instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.titleLabel.textAlignment = NSTextAlignmentCenter;
self.titleLabel.font = [UIFont systemFontOfSize:15];
[self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
// 如果沒有提供圖片我們可以設置buton width height 分別減1;
[self setBackgroundImage:[UIImage imageNamed:@"mainCellBackground"] forState:UIControlStateNormal];
}
return self;
}
另外,因為點擊CLMeSquareButton,我們要拿到模型中的url,進行跳轉或者http請求,所以給button添加一個CLMeSquare模型屬性,并且可以通過CLMeSquare的set方法來給CLMeSquareButton中imageView和titleLabel賦值
-(void)setSquare:(CLMeSquare *)square
{
// 通過bubtton 的屬性 square的set方法,拿到square后給button的圖片和文字賦值 。
_square = square;
// 設置所有button的圖片和文字
[self setTitle:square.name forState:UIControlStateNormal];
[self sd_setImageWithURL:[NSURL URLWithString:square.icon] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"header_cry_icon"]];
}
最后就是按鈕點擊事件的實現,需要對參數url進行判斷,根據不同的url進行不同的操作,如果是mod開頭的就跳轉到其他界面,如果是http開頭的就需要加載網頁。
- 對開頭字母的判斷
// 判斷是否以http開頭
[square.url hasPrefix:@"http"]
//延伸: [square.url hasSuffix:@"http"] 判斷是否以http結尾
- 如何加載webViewController,并跳轉到webViewController
加載webViewController很簡單,創建webViewController并將url賦值給他即可。
CLWebViewController *webVc = [[CLWebViewController alloc]init];
webVc.url = square.url;
在自定義的footView中,跳轉到webViewController,首先需要拿到NavgationController通過push方法進行跳轉,如果想拿到NavgationController,需要拿到tabBarController,tabBarController的selectedViewController,即可拿到當前選擇的NavgationController,而tabBarController我們可以通過窗口的跟控制器拿到。
UITabBarController *tabBarVC = (UITabBarController *)self.window.rootViewController;
UINavigationController *naVC = tabBarVC.selectedViewController;
webVc.navigationItem.title = square.name;
[naVC pushViewController:webVc animated:YES];
- 另外iOS9之后引入
#import <SafariServices/SafariServices.h>
可以使用系統的Safari來進行網頁加載,并且功能非常齊全,可以前進,后退,刷新還可以顯示進度條。但是注意:只有mode出來的Safari才會顯示進度條等控件。
SFSafariViewController *webView = [[SFSafariViewController alloc]initWithURL:[NSURL URLWithString:square.url]];
UITabBarController *tabBarVC = (UITabBarController *)self.window.rootViewController;
[tabBarVC presentViewController:webView animated:YES completion:nil];
此時,整個界面基本上已經完成了,接下來完成點擊又上角設置按鈕,進入設置界面,清除緩存功能。
清除緩存功能
首先來看一下設置界面
首先設置界面涉及到兩種不同類型cell共存的問題,很明顯第一行清除緩存cell與下面的cell類型不同,如果所有cell放到同一個緩存池中,當清除緩存cell復用到下面的cell時,需要去掉右邊箭頭,當清除緩存cell重新加載時,又需要加上右邊箭頭,并且清除緩存內部是需要做清除緩存功能的,而其他cell不需要這個功能,所以當一個cell是特有的,與其他cell不一樣,業務邏輯也需要被獨立的封裝起來,為了避免復雜重復的操作,這種cell最好獨立出來,并且不要循環給別的cell。
我們通過使用兩種獨立類型的cell,使用不同的標識來區分兩種cell,一種標識就對應一種cell 通過一種標識來找一種cell的時候,如果沒有那么創建一個cell,通過另外一種標識來找cell 的時候,就會創建另外一種cell,如果緩存池中有就去自己標識的緩存池中取。
由此類推多種不同的cell,對應多種不同的標識。每種類型的cell,創建并緩存到自己對應標識的緩存池中。
這里設置界面自定義兩種cell,清除緩存的CLClearCacheCell,其他類型的CLSettingCell,兩種cell都需要進行注冊
static NSString * const CLClearCacheCellId = @"CLClearCacheCell";
static NSString * const CLSettingCellId = @"CLSettingCellId";
// 注冊cell
[self.tableView registerClass:[CLClearCacheCell class] forCellReuseIdentifier:CLClearCacheCellId];
[self.tableView registerClass:[CLSettingCell class] forCellReuseIdentifier:CLSettingCellId];
當使用時,按照不同的行區分需要顯示的不同類型的cell
// 按照不同的標識 重用不同的cell
// 取出cell,這里第0行是清除緩存cell,其他行是其他cell
if (indexPath.row == 0) {
CLClearCacheCell *cell = [tableView dequeueReusableCellWithIdentifier:CLClearCacheCellId];
return cell;
}else{
CLSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:CLSettingCellId];
cell.textLabel.text = @"haha";
return cell;
}
另外,我們需要給CLClearCacheCell添加tap手勢,確保緩存文件大小計算完畢之后,才可以點擊CLClearCacheCell清除緩存,當給cell添加tap手勢之后,就會自動覆蓋cell的代理方法tableView: didSelectRowAtIndexPath
。
接下來是將清除緩存業務邏輯封裝到CLClearCacheCell中,首先清除緩存是清除沙盒中Caches中的文件,并且通過代碼刪除是不可逆的。來看一下沙盒中Caches文件內容
其中custom是我們自己創建的用來緩存的文件夾,default是SD創建的圖片緩存文件,我們需要將這兩個文件夾內容大小計算出來,計算文件夾的大小,本質上就是遍歷文件夾里面所有文件并計算文件大小,最后累加計算出文件夾總的大小。之后就是清除緩存,清除緩存的本質就是刪掉這兩個文件,并重新創建新的文件夾。
SD提供了計算dufault文件大小和刪除文件的方法。引入#import <SDImageCache.h>
// 獲取文件大小
[SDImageCache sharedImageCache].getSize
//
// clear清除所有圖片文件
[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
// 清除之后要做的事兒
}];
// clearn 只清除時間超過一周的文件
[[SDImageCache sharedImageCache] cleanDiskWithCompletionBlock:^{
// 清除之后要做的事兒
}];
接下來我們要仿照SD清除緩存的內部實現來做我們自己創建的文件custom的清除緩存功能。首先計算文件大小
// 總大小
unsigned long long size = 0;
// 獲取緩存文件路徑
NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
// 拼接全文件路徑
NSString *filePath = [cachesPath stringByAppendingPathComponent:@"custom"];
// 創建文件管理者
NSFileManager *manager = [NSFileManager defaultManager];
// 使用遍歷器獲得custom文件下所有文件的子路徑
NSDirectoryEnumerator *enumerator = [manager enumeratorAtPath:filePath];
for (NSString *subpath in enumerator) {
// 拼接成完整路徑
NSString *fullParh = [filePath stringByAppendingPathComponent:subpath];
// 獲取文件屬性字典
NSDictionary *attribute = [manager attributesOfItemAtPath:fullParh error:nil];
// 累加文件大小
size += attribute.fileSize;
}
也可以通過獲得子路徑數組進行遍歷
NSArray *subpaths = [manager subpathsAtPath:filePath];
for (NSString *subpath in subpaths) {
// 拼接成完整路徑
NSString *fullParh = [filePath stringByAppendingPathComponent:subpath];
// 獲取文件屬性字典
NSDictionary *attribute = [manager attributesOfItemAtPath:fullParh error:nil];
//size += [attribute[NSFileSize] unsignedIntegerValue];
// fileSize方法返回的就是 NSFileSize 對應的key
//累加文件大小
size += attribute.fileSize;
}
刪除costum文件并重新創建空的文件夾
#define CLCustomCacheFile [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"custom"]
NSFileManager *manager = [NSFileManager defaultManager];
// 刪除文件
[manager removeItemAtPath:CLCustomCacheFile error:nil];
// 創建文件 withIntermediateDirectories:YES 表示如果沒有中間文件會自動創建,NO 表示不會自動創建中間文件,如果發現沒有文件則不會創建
[manager createDirectoryAtPath:CLCustomCacheFile withIntermediateDirectories:YES attributes:nil error:nil];
注意:計算文件大小和刪除文件并重新創建都數據耗時操作,要放到子線程中去執行。
自定義CLClearCacheCell還有一些其他的邏輯需要注意。
- 等設置完文字之后在禁止cell點擊,如果直接禁止點擊,字體顏色會被渲染成灰色,文件大小計算完畢之后在開啟點擊。
- 先顯示正在計算的小菊花,等計算完畢之后關閉小菊花,顯示箭頭,這里有一個注意點,accessoryView比accessoryType優先級要高,所以顯示箭頭的時候,需要先將accessoryView至為空然后在設置accessoryType。并且當正在計算時,將第一行cell滑出屏幕,在返回時發現小菊花已經不在了,我們可以通過重寫cell的layoutSubviews,重新設置cell小菊花start,因為每當cell顯示的時候都會調用layoutSubviews方法。
- 計算文件大小,顯示在cell上,根據不同的大小顯示不同的單位GB,MB,KB等。
- 點擊cell清除緩存,可以先清除SD的圖片緩存,SD緩存清除完畢之后在,在開子線程清除其他文件的緩存,之后在回到主線程刷新cell的內容。
- cell的銷毀時刻,當進入設置控制器,正在計算文件大小時,返回,此時設置控制器已經被銷毀。但是cell會等子線程任務執行完畢之后才會被銷毀,因為還要用到cell且block中強引用了strong的對象,所以不會讓cell銷毀。所以在block中使用弱引用,block內部就不會對那個對象產生強引用。其該釋放的時候就會被釋放,雖然已經釋放,但是代碼還是會往下面執行,此時對象為空。
- 點擊清除按鈕的時候使用SVProgressHUD彈出提醒框,清除完畢之后關閉提醒框。
理解了這些來看一下CLClearCacheCell的代碼
#define CLCustomCacheFile [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"custom"]
@implementation CLClearCacheCell
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
self.textLabel.text = @"清除緩存(正在計算文件大小...)";
// 等設置完文字之后在禁止點擊,如果直接禁止點擊 字體顏色會被渲染成灰色
self.userInteractionEnabled = NO;
// 設置小菊花
UIActivityIndicatorView *indicatorView =[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[indicatorView startAnimating];
self.accessoryView = indicatorView;
// 創建弱引用對象
__weak typeof(self) weakSelf = self;
// 開啟子線程計算文件大小
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// mac中換算MB 除以1000,并不是以1024為單位
// 總大小
unsigned long long size = 0;
NSArray *subpaths = [manager subpathsAtPath:CLCustomCacheFile];
for (NSString *subpath in subpaths) {
// 拼接成完整路徑
NSString *fullParh = [filePath stringByAppendingPathComponent:subpath];
// 獲取文件屬性字典
NSDictionary *attribute = [manager attributesOfItemAtPath:fullParh error:nil];
// 累加文件大小
size += attribute.fileSize;
}
size = size+ [SDImageCache sharedImageCache].getSize;
// 判斷cell是否已經被銷毀,如果銷毀了就直接返回
if (weakSelf == nil) {
return ;
}
NSString *sizeText = nil;
if (size >= pow(10, 9)) {
sizeText = [NSString stringWithFormat:@"%.1fGB",size / 1000.0 / 1000.0 / 1000.0];
}else if (size >= pow(10, 6)){
sizeText = [NSString stringWithFormat:@"%.1fMB",size / 1000.0 / 1000.0];
}else if (size >= pow(10, 3)){
sizeText = [NSString stringWithFormat:@"%.1fKB",size / 1000.0];
}else{
sizeText = [NSString stringWithFormat:@"%zdB",size];
}
NSString *text = [NSString stringWithFormat:@"清除緩存(%@)",sizeText];
// 回到主線程刷新cell
dispatch_async(dispatch_get_main_queue(), ^{
weakSelf.textLabel.text = text;
weakSelf.accessoryView = nil;
weakSelf.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
weakSelf.userInteractionEnabled = YES;
// 等計算完緩存大小之后在添加手勢,保證正在計算過程中cell 點擊無效
[weakSelf addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:weakSelf action:@selector(celltap:)]];
});
});
}
return self;
}
// cell點擊手勢
-(void)celltap:(UITapGestureRecognizer *)tap
{
[SVProgressHUD showWithStatus:@"正在清除緩存"];
// 清除所有圖片文件 clearn 只清除時間超過一周的文件
[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
// 清除之后要做的事兒
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSFileManager *manager = [NSFileManager defaultManager];
[manager removeItemAtPath:CLCustomCacheFile error:nil];
//withIntermediateDirectories:YES ,表示中間文件如果沒有會自動創建,NO 也不會自動創建中間文件,如果發現沒有文件則不會創建
[manager createDirectoryAtPath:CLCustomCacheFile withIntermediateDirectories:YES attributes:nil error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
// 隱藏指示器
[SVProgressHUD dismiss];
self.textLabel.text = @"清除緩存(0B)";
});
});
}];
}
// 每當cell 重新顯示在桌面上 ,都會調用laoutsubviews
-(void)layoutSubviews
{
[super layoutSubviews];
UIActivityIndicatorView *indicator = (UIActivityIndicatorView *)self.accessoryView;
[indicator startAnimating];
}
@end
方法抽取總結
獲取文件大小需要經常用到的,可以通過給NSString添加分類方法將獲取文件大小的方法抽取出來,使用文件路徑直接調用fileSize方法即可獲得文件大小。
NSString+CLExtension.h
#import <Foundation/Foundation.h>
@interface NSString (CLExtension)
-(unsigned long long)fileSize;
@end
NSString+CLExtension.m
#import "NSString+CLExtension.h"
@implementation NSString (CLExtension)
-(unsigned long long)fileSize
{
unsigned long long size = 0;
NSFileManager *manager = [NSFileManager defaultManager];
BOOL directory = NO;
BOOL exists = [manager fileExistsAtPath:self isDirectory:&directory];
// 如果地址為空
if (!exists) return size;
// 如果是文件夾
if (directory) {
NSDirectoryEnumerator *enumerator = [manager enumeratorAtPath:self];
for (NSString *path in enumerator) {
NSString *fullPath = [self stringByAppendingPathComponent:path];
NSDictionary *attr = [manager attributesOfItemAtPath:fullPath error:nil];
size += attr.fileSize;
}
}else{
size = [manager attributesOfItemAtPath:self error:nil].fileSize;
}
return size;
}
@end
這樣當需要獲取文件大小的時候,直接使用路徑.fileSize
就可以獲得文件大小了,非常方便。并且這個方法在別的項目中也經常會用到,快將這個方法添加到你的代碼庫中吧。
總結
今天主要完成了我的界面的搭建,主要內容CocoaPods的使用以及AFN,SD,MJExtension等第三方框架的簡單使用,tableView的footView的布局和顯示,webView的加載,多種cell共存的實現,清除緩存功能的實現等,其中有許多細節問題需要注意。
第三天效果如下
文中如果有不對的地方歡迎指出。我是xx_cc,一只長大很久但還沒有二夠的家伙。