DJStatusPhotosView.h
#import <UIKit/UIKit.h> @interface DJStatusPhotosView : UIView @property (nonatomic,strong) NSArray *photos; /** 根据相册图片个数计算相册尺寸 */ + (CGSize)sizeWithCount:(NSUInteger)count; @end
DJStatusPhotosView.m
#import "DJStatusPhotosView.h" #import "UIImageView+WebCache.h" #import "DJPhoto.h" // 相册的最大列数 #define DJStatusPhotosViewMaxColumns 3 // 相册中的图片间距 #define DJStatusPhotosViewMargin 4 // 相册图片的宽高 #define DJStatusPhotoWH ((DJContentWidth - (DJStatusPhotosViewMaxColumns - 1) * DJStatusPhotosViewMargin) / DJStatusPhotosViewMaxColumns) @implementation DJStatusPhotosView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // self.backgroundColor = [UIColor redColor]; } return self; } + (CGSize)sizeWithCount:(NSUInteger)count { // 相册列数 NSUInteger cols = (count >= DJStatusPhotosViewMaxColumns ) ? DJStatusPhotosViewMaxColumns : count; // 相册宽度 CGFloat photosW = cols * DJStatusPhotoWH + (cols-1) * DJStatusPhotosViewMargin; /* * 补充公式: * 一共268条数据,每页18条,共有多少页,计算公式如下 * int pages = (totalCount + maxNumsInPage - 1) / maxNumsInPage */ // 相册行数 NSUInteger rows = (count + DJStatusPhotosViewMaxColumns - 1) / DJStatusPhotosViewMaxColumns; CGFloat photosH = rows * DJStatusPhotoWH + (rows-1) * DJStatusPhotosViewMargin; return CGSizeMake(photosW,photosH); } - (void)setPhotos:(NSArray *)photos { _photos = photos; // 添加和创建所需的UIImageView,并且设置图片的显示内容 NSUInteger photosCount = photos.count; // 令相册里的photoView的个数始终满足待显示的需要,若数组中的图片个数大于相册中现有的个数,则创建新的photoView while (self.subviews.count < photosCount) { UIImageView *photoView = [[UIImageView alloc] init]; [self addSubview:photoView]; } // 设置相册中的imageView的显示内容 for (int i = 0; i < self.subviews.count; i++) { UIImageView *photoView = self.subviews[i]; if (i >= photosCount) { // 当前photoView多余,将其hidden属性置为YES,因为tableView的cell会重复利用 photoView.hidden = YES; } else { photoView.hidden = NO; DJPhoto *photo = photos[i]; [photoView sd_setImageWithURL:[NSURL URLWithString:photo.thumbnail_pic] placeholderImage:[UIImage imageNamed:@"timeline_image_placeholder"]]; } } } // 在此方法中设置相册中单个图片的frame - (void)layoutSubviews { [super layoutSubviews]; for (int i = 0; i < self.photos.count; i++) { UIImageView *photoView = self.subviews[i]; int col = i % DJStatusPhotosViewMaxColumns; photoView.x = col * (DJStatusPhotoWH + DJStatusPhotosViewMargin); int row = i / DJStatusPhotosViewMaxColumns; photoView.y = row * (DJStatusPhotoWH + DJStatusPhotosViewMargin); photoView.width = DJStatusPhotoWH; photoView.height = DJStatusPhotoWH; } } @end
最终效果:
原文:http://www.cnblogs.com/yongdaimi/p/6091336.html