1000memories 已在 MIT 協議下開源了它的 iOS 瀑布流視圖控件「quilt」。所謂瀑布流,就是以不同的長寬比在多個欄位中排列圖片與媒體,這是 1000memories 網站以及 iPhone、Android 版 ShoeBox 的設計美學核心,能給人一種真實相冊的質感,並突顯老照片的味道。
開場白說完,我們直接進入實作。
先到 GitHub 下載開原始碼。你會發現壓縮檔裡有好幾個資料夾,接著把指定路徑下的 6 個檔案直接拖進你的工程即可,不需要像 demo 那樣加入這麼多檔案。
前往要實作的類別,在標頭檔中加入以下程式碼:
#import <UIKit/UIKit.h>
#import "TMQuiltView.h"
@interface WaterFlowVC : UIViewController<TMQuiltViewDataSource,TMQuiltViewDelegate>
{
TMQuiltView *_tmQuiltView;
NSMutableArray *_images;
}
@property (nonatomic,retain)TMQuiltView *tmQuiltView;
@property (nonatomic,retain)NSMutableArray *images;
@end
其中 tmQuiltView 就是 1000memories 定義的瀑布流控件,從加入的協議就能看出它和 tableView 相當類似;_images 則是存放圖片的資料來源陣列。
接著在 .m 檔中完成資料來源與代理方法:
#pragma mark -
#pragma mark TMQuiltViewDataSource
-(NSInteger)quiltViewNumberOfCells:(TMQuiltView *)TMQuiltView
{
return [self.images count];
}
-(TMQuiltViewCell *)quiltView:(TMQuiltView *)quiltView cellAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifierStr = @"photoIdentifier";
TMPhotoQuiltViewCell *cell = (TMPhotoQuiltViewCell *)[quiltView dequeueReusableCellWithReuseIdentifier:identifierStr];
if (!cell)
{
cell = [[[TMPhotoQuiltViewCell alloc] initWithReuseIdentifier:identifierStr] autorelease];
}
cell.photoView.image = [self imageAtIndexPath:indexPath];
cell.titleLabel.text = [NSString stringWithFormat:@"%d", indexPath.row + 1];
return cell;
}
#pragma mark -
#pragma mark TMQuiltViewDelegate
//列數
- (NSInteger)quiltViewNumberOfColumns:(TMQuiltView *)quiltView
{
return 2;
}
//單元高度
- (CGFloat)quiltView:(TMQuiltView *)quiltView heightForCellAtIndexPath:(NSIndexPath *)indexPath {
float height = [self imageAtIndexPath:indexPath].size.height / [self quiltViewNumberOfColumns:quiltView];
return height;
}
資料來源與代理需要的方法就這麼多,若有其他需求,可以跳到定義資料來源與代理的類別中查看。demo 裡把 -(NSArray *)images 與 - (UIImage *)imageAtIndexPath:(NSIndexPath *)indexPath 兩個方法也寫進資料來源,但要注意這兩者並非資料來源方法。其中的 TMPhotoQuiltViewCell 是從 demo 複製出來的自訂單元,你可以依需求改成自己想要的外觀。整體代理方法與 tableView 十分相似,因此相當容易上手。
最後在 viewDidLoad 中完成初始化:
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
_tmQuiltView = [[TMQuiltView alloc] init];
_tmQuiltView.frame = CGRectMake(0, 0, 320, [[UIScreen mainScreen] bounds].size.height-20-44);
_tmQuiltView.delegate = self;
_tmQuiltView.dataSource = self;
[self.view addSubview:_tmQuiltView];
[_tmQuiltView reloadData];
NSMutableArray *imageNames = [[NSMutableArray alloc] init];
for (int i = 0; i< kNumberOfCells;i++ )
{
[imageNames addObject:[NSString stringWithFormat:@"%d.jpeg",i % 10 + 1]];
}
self.images = imageNames;
[imageNames release];
[_tmQuiltView reloadData];
}