項目須要,前一陣子重構了下iPad工程,添加了一個滾動無縫日曆。git
當時沒有頭緒,網上找了一個源碼改吧改吧就上線了(參考連接),這個功能不少並且流暢性也特別好,推薦不會寫的能夠參考下。github
這幾天,活不太忙就把日曆控件裁剪了下,作個最簡單的滾動無縫日曆。效果以下圖:ide
日曆能夠左右滾動,點擊某個日期後會變色,而且有回調。橘色的是標記日期,藍色的是選擇日期,藍邊的是當前日期,能夠根據須要自行更改。atom
這個日曆控件有兩個比較複雜的地方:spa
#import "EXCalendarCollectionViewFlowLayout.h" @interface EXCalendarCollectionViewFlowLayout () @property (nonatomic, strong) NSMutableArray *allAttributes; @end @implementation EXCalendarCollectionViewFlowLayout - (void)prepareLayout { [super prepareLayout]; self.allAttributes = [NSMutableArray array]; NSInteger sections = [self.collectionView numberOfSections]; for (int i = 0; i < sections; i++) { // setup one section attributes. NSMutableArray *tmpArray = [NSMutableArray array]; NSInteger count = [self.collectionView numberOfItemsInSection:i]; for (NSInteger j = 0; j < count; j++) { NSIndexPath *indexPath = [NSIndexPath indexPathForItem:j inSection:i]; UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath]; [tmpArray addObject:attributes]; } [self.allAttributes addObject:tmpArray]; } } - (CGSize)collectionViewContentSize { return [super collectionViewContentSize]; } - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath { NSInteger item = indexPath.item; NSInteger x; NSInteger y; // 根據item的序號計算出item的行列位置 [self targetPositionWithItem:item resultX:&x resultY:&y]; // 根據已得出的item的行列位置,將item放入indexPath中對應的位置。 NSInteger item2 = [self orignItemAtX:x y:y]; NSIndexPath *theNewIndexPath = [NSIndexPath indexPathForItem:item2 inSection:indexPath.section]; UICollectionViewLayoutAttributes *theNewAttr = [super layoutAttributesForItemAtIndexPath:theNewIndexPath]; theNewAttr.indexPath = indexPath; return theNewAttr; } - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect { NSArray *attributes = [super layoutAttributesForElementsInRect:rect]; NSMutableArray *tmp = [NSMutableArray array]; for (UICollectionViewLayoutAttributes *attr in attributes) { for (NSMutableArray *attributes in self.allAttributes) { for (UICollectionViewLayoutAttributes *attr2 in attributes) { if (attr.indexPath.item == attr2.indexPath.item) { [tmp addObject:attr2]; break; } } } } return tmp; } // 根據item計算目標item的位置。 - (void)targetPositionWithItem:(NSInteger)item resultX:(NSInteger *)x resultY:(NSInteger *)y { // NSInteger page = item / (self.itemCountPerRow * self.rowCountPerPage); NSInteger theX = item % self.itemCountPerRow; NSInteger theY = item / self.itemCountPerRow; if (x != NULL) { *x = theX; } if (y != NULL) { *y = theY; } } - (NSInteger)orignItemAtX:(NSInteger)x y:(NSInteger)y { NSInteger item = x * self.rowCountPerPage + y; return item; } @end