溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

iOS如何使用UICollectionView實(shí)現(xiàn)橫向滾動(dòng)照片效果

發(fā)布時(shí)間:2021-09-27 15:22:37 來源:億速云 閱讀:97 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)iOS如何使用UICollectionView實(shí)現(xiàn)橫向滾動(dòng)照片效果的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

思路

1. 界面搭建

界面的搭建十分簡(jiǎn)單,采用UICollectionView和自定義cell進(jìn)行搭建即可。

// ViewController.m// 下面使用到的宏和全局變量#define ScreenW [UIScreen mainScreen].bounds.size.width#define ScreenH [UIScreen mainScreen].bounds.size.heightstatic NSString *const cellID = @"cellID";// 創(chuàng)建collectionView的代碼- (void)setupCollectionView{ // 使用系統(tǒng)自帶的流布局(繼承自UICollectionViewLayout) UICollectionViewFlowLayout *layout = ({  UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];  // 每個(gè)cell的大小  layout.itemSize     = CGSizeMake(180, 180);  // 橫向滾動(dòng)  layout.scrollDirection    = UICollectionViewScrollDirectionHorizontal;  // cell間的間距  layout.minimumLineSpacing   = 40;  //第一個(gè)cell和最后一個(gè)cell居中顯示(這里我的Demo里忘記改了我用的是160,最后微調(diào)數(shù)據(jù)cell的大小是180)  CGFloat margin = (ScreenW - 180) * 0.5;  layout.sectionInset    = UIEdgeInsetsMake(0, margin, 0, margin);  layout; }); // 使用UICollectionView必須設(shè)置UICollectionViewLayout屬性 UICollectionView *collectionView = ({  UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];  collectionView.center   = self.view.center;  collectionView.bounds   = CGRectMake(0, 0, ScreenW, 200);  collectionView.backgroundColor = [UIColor brownColor];  // 這里千萬記得在interface哪里寫<UICollectionViewDataSource>!?。? collectionView.dataSource  = self;  [collectionView setShowsHorizontalScrollIndicator:NO];  [self.view addSubview:collectionView];  collectionView; }); // 實(shí)現(xiàn)注冊(cè)cell,其中PhotoCell是我自定義的cell,繼承自UICollectionViewCell UINib *collectionNib = [UINib nibWithNibName:NSStringFromClass([PhotoCell class])           bundle:nil]; [collectionView registerNib:collectionNib  forCellWithReuseIdentifier:cellID];}// UICollectionViewCellDataSource- (NSInteger)collectionView:(UICollectionView *)collectionView  numberOfItemsInSection:(NSInteger)section{ return 10;}- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView       cellForItemAtIndexPath:(NSIndexPath *)indexPath{ PhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID       forIndexPath:indexPath]; // 圖片名是 0 ~ 9 cell.imageName = [NSString stringWithFormat:@"%ld", (long)indexPath.row]; return cell;}

// 界面是一個(gè)xib文件,在cell里拖了個(gè)ImageView,約束上下左右都是10// 圖片名是數(shù)字 0 ~ 9// PhotoCell.h@property (nonatomic, strong) NSString *imageName;// PhotoCell.m@interface PhotoCell ()@property (weak, nonatomic) IBOutlet UIImageView *imageView;@end@implementation PhotoCell- (void)awakeFromNib { [super awakeFromNib]; // Initialization code}- (void)setImageName:(NSString *)imageName{ _imageName = imageName; self.imageView.image = [UIImage imageNamed:imageName];}

到這里最基礎(chǔ)的效果就實(shí)現(xiàn)完了,一組大小相等的圖片cell。

2.大小變化已經(jīng)居中效果實(shí)現(xiàn)

由于系統(tǒng)的UICollectionViewFlowLayout無法實(shí)現(xiàn)我想要的效果,因此我重寫下該類中的某些方法。 在UICollectionViewLayout中有這樣兩句注釋:

1. Methods in this class are meant to be overridden and will be called by its collection view to gather layout information. 在這個(gè)類中的方法意味著被重寫(overridden),并且將要被它的 collection view 調(diào)用,用于收集布局信息

2. To get the truth on the current state of the collection view, call methods on UICollectionView rather than these. 要獲取 collection view 的當(dāng)前狀態(tài)的真相,調(diào)用UICollectionView上的方法,而不是這些其中有一點(diǎn)需要解釋下,collectionView的bounds的x和y實(shí)際上就是collectionView的內(nèi)容視圖的 x和y。關(guān)于這點(diǎn),請(qǐng)看我寫的一篇博文的解釋:iOS bounds學(xué)習(xí)筆記以及仿寫UIScrollView的部分功能

// MyFlowLayout.h#import <UIKit/UIKit.h>// 注意!繼承自UICollectionViewFlowLayout,因?yàn)樗^承自UICollectionViewLayout。@interface TWLayout : UICollectionViewFlowLayout// MyFlowLayout.m/** * The default implementation of this method returns NO. Subclasses can override it and return an appropriate value based on whether changes in the bounds of the collection view require changes to the layout of cells and supplementary views.  此方法的默認(rèn)實(shí)現(xiàn)返回NO。 子類可以覆蓋它,并根據(jù) collection view 的 bounds 中的更改是否需要更改 cells 和 supplementary views(補(bǔ)充視圖) 的布局返回適當(dāng)?shù)闹怠?* If the bounds of the collection view change and this method returns YES, the collection view invalidates the layout by calling the invalidateLayoutWithContext: method.  如果 collection view 的 bounds 更改并且此方法返回YES,則 collection view 通過調(diào)用invalidateLayoutWithContext:方法使布局更新。 @param newBounds The new bounds of the collection view. @return YES if the collection view requires a layout update or NO if the layout does not need to change. */- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{ return YES;}/** * Returns the layout attributes for all of the cells and views in the specified rectangle. 返回指定矩形中所有cells和views的布局屬性。 @param rect * The rectangle (specified in the collection view's coordinate system) containing the target views.    包含目標(biāo)視圖的矩形(在集合視圖的坐標(biāo)系中指定)。 @return * An array of UICollectionViewLayoutAttributes objects representing the layout information for the cells and views. The default implementation returns nil.   UICollectionViewLayoutAttributes對(duì)象數(shù)組,表示cell和view的布局信息。默認(rèn)實(shí)現(xiàn)返回nil。 */- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{ // 獲取collectionView的寬帶 CGFloat collectionW = self.collectionView.bounds.size.width; // 獲取布局屬性數(shù)組 NSArray<UICollectionViewLayoutAttributes *> *attrs = [super layoutAttributesForElementsInRect:self.collectionView.bounds]; for (int i = 0; i < attrs.count; i++) {  UICollectionViewLayoutAttributes *attr = attrs[i];  //每個(gè)顯示的cell距離中心距離  CGFloat margin = fabs((attr.center.x - self.collectionView.contentOffset.x) - collectionW * 0.5);  // 縮放比例:(margin / (collectionW * 0.5))得出的結(jié)論相當(dāng)于 0 ~ 1。而我們需要它的縮放比例是 1 ~ 0.65,這樣就是 (1 - 0)~(1 - 0.35)  CGFloat scale = 1 - (margin / (collectionW * 0.5)) * 0.35;  attr.transform = CGAffineTransformMakeScale(scale, scale); } return attrs;}/** * Returns the point at which to stop scrolling. * 關(guān)于這個(gè)方法,最終的偏移量,并不是由手指滑動(dòng)過的偏移量決定的。如果手指滑動(dòng)比較快,手指滑動(dòng)過后,視圖還會(huì)多滾動(dòng)一段距離;如果手指滑動(dòng)緩慢,手指滑到何處,就停到何處。 @param proposedContentOffset 建議的點(diǎn)(在集合視圖的內(nèi)容視圖的坐標(biāo)空間中)用于可見內(nèi)容的左上角。 這表示集合視圖計(jì)算為在動(dòng)畫結(jié)束時(shí)最可能使用的值。 @param velocity 沿著水平軸和垂直軸的當(dāng)前滾動(dòng)速度。 該值以每秒點(diǎn)數(shù)為單位。 @return 要使用的內(nèi)容偏移量。 此方法的默認(rèn)實(shí)現(xiàn)返回proposedContentOffset參數(shù)中的值。 */- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{ // 獲取collectionView的寬度 CGFloat collectionW = self.collectionView.bounds.size.width; // 獲取當(dāng)前的內(nèi)容偏移量 CGPoint targetP = proposedContentOffset; // 獲取顯示cell的布局屬性數(shù)組,橫向滾動(dòng),所以只用考慮橫向的x和width,縱向不用考慮 NSArray *attrs = [super layoutAttributesForElementsInRect:CGRectMake(targetP.x, 0, collectionW, MAXFLOAT)]; // 距離中心點(diǎn)最近的cell的間距(中間那個(gè)cell距離最近,值可正可負(fù)) CGFloat minSpacing = MAXFLOAT; for (UICollectionViewLayoutAttributes *attr in attrs) {  // 距離中心點(diǎn)的偏移量  CGFloat centerOffsetX = attr.center.x - targetP.x - collectionW * 0.5;  // fabs():CGFloat絕對(duì)值  if (fabs(centerOffsetX) < fabs(minSpacing)) {   minSpacing = centerOffsetX;  } } targetP.x += minSpacing; return targetP;}

最后,記得把 UICollectionViewFlowLayout 改成你自定義的FlowLayout對(duì)象??!

感謝各位的閱讀!關(guān)于“iOS如何使用UICollectionView實(shí)現(xiàn)橫向滾動(dòng)照片效果”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI