Objective-C
最終效果:
- 圖片水平滾動(dòng)
- 圖片初始位置在屏幕中間
- 滑動(dòng)到最左和最右時(shí)圖片停留在屏幕最中間.
- 中間任意位置停止滑動(dòng)時(shí), 總有一個(gè)圖片顯示在屏幕的最中間
實(shí)現(xiàn)原理
- 使用自定義布局,這里創(chuàng)建自定義類(lèi)LineLayout繼承自流水布局
UICollectionViewFlowLayout
#import "LineLayout.h"
@implementation LineLayout
/** collectView會(huì)在布局時(shí)調(diào)用該方法 */
- (void)prepareLayout
{
[super prepareLayout];
/** 設(shè)置滾動(dòng)方向?yàn)樗綕L動(dòng) */
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
/** 設(shè)置內(nèi)間距, 保證左右兩邊的顯示的圖片在collectView的最中間 */
CGFloat inset = (self.collectionView.frame.size.width - self.itemSize.width) * 0.5;
self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);
}
/** 返回YES時(shí), 每次滾動(dòng)都會(huì)調(diào)用layoutAttributesForElementsInRect:方法; 默認(rèn)返回NO,即輕微的滾動(dòng)不會(huì)調(diào)用layoutAttributesForElementsInRect:方法 */
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return YES;
}
/**
* 1.一個(gè)cell對(duì)應(yīng)一個(gè)UICollectionViewLayoutAttributes對(duì)象;
* 2.UICollectionViewLayoutAttributes對(duì)象決定了cell的frame;
*
* layoutAttributesForElementsInRect:
* 返回值為一個(gè)數(shù)組,里面存放著rect范圍內(nèi)所有元素的布局屬性;
* 返回值也就決定了rect范圍內(nèi)所有元素的排布(frame);
*/
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
// 調(diào)用super, 獲得計(jì)算好的屬性值
NSArray *attrs = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes *attr in attrs)
{
// collectView的中心點(diǎn)x = 偏移量 + 自身寬度的一半
CGFloat collectViewCenterX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;
// cell的中心點(diǎn)x = 偏移量 + cell寬度的一半 = attr.center.x
CGFloat cellCenterX = attr.center.x;
// 計(jì)算cell的中心點(diǎn)到collectView中心點(diǎn)的距離(距離越近,尺寸越大)
CGFloat delta = ABS(cellCenterX - collectViewCenterX);
// 計(jì)算縮放比例
CGFloat scale = 1 - delta / self.collectionView.frame.size.width;;
// 設(shè)置縮放
attr.transform = CGAffineTransformMakeScale(scale, scale);
}
return attrs;
}
/**
* 作用: 讓collectView停止?jié)L動(dòng)時(shí)總有一個(gè)cell顯示在屏幕的最中間.
*
* @return 返回值決定了collectionView停止?jié)L動(dòng)時(shí)的偏移量
*/
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
// 獲得最終的矩形框frame
CGRect rect;
rect.origin.x = proposedContentOffset.x;
rect.origin.y = 0;
rect.size = self.collectionView.frame.size;
NSArray *attrs = [self layoutAttributesForElementsInRect:rect];
// 計(jì)算collectView最中心點(diǎn)的x的值
CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width * 0.5;
// 計(jì)算cell的的中心點(diǎn)x距離collectView中心x的最小值
CGFloat minDelta = MAXFLOAT;
for (UICollectionViewLayoutAttributes *attr in attrs) {
if (ABS(attr.center.x - centerX) < ABS(minDelta) ){
minDelta = attr.center.x - centerX;
}
}
// 修改最終的偏移量
proposedContentOffset.x += minDelta;
return proposedContentOffset;
}
@end
- 創(chuàng)建collectView, 并設(shè)置創(chuàng)建好的自定義布局
#import "ViewController.h"
#import "LineLayout.h"
#import "LVPictureCell.h"
@interface ViewController () <UICollectionViewDataSource, UICollectionViewDelegate>
@end
static NSString *ID = @"mycell";
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/** 設(shè)置背景色 */
self.view.backgroundColor = [UIColor redColor];
/** 設(shè)置狀態(tài)欄文字顏色 */
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
/** 創(chuàng)建布局 */
LineLayout *layout = [[LineLayout alloc] init];
/** 設(shè)置cell的大小 */
layout.itemSize = CGSizeMake(250 * 0.5, 370 * 0.5);
/** 設(shè)置collectView的frame */
CGRect frame = CGRectMake(0, 100, self.view.frame.size.width, 370);
/** 創(chuàng)建collectView */
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
/** 注冊(cè)cell */
[collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LVPictureCell class]) bundle:nil] forCellWithReuseIdentifier:ID];
/** collectView的背景色 */
collectionView.backgroundColor = [UIColor blackColor];
/** 設(shè)置collectView的代理和數(shù)據(jù)源 */
collectionView.dataSource = self;
collectionView.delegate = self;
/** collectView添加到當(dāng)前view上 */
[self.view addSubview:collectionView];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
LVPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
cell.imageName = [NSString stringWithFormat:@"%zd",indexPath.item];
return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 13;
}
@end
Swift
1. 自定義布局
private class NewFeatureLayout: UICollectionViewFlowLayout {
override func prepareLayout()
super.prepareLayout()
itemSize = UIScreen.mainScreen().bounds.size
minimumInteritemSpacing = 0
minimumLineSpacing = 0
scrollDirection = UICollectionViewScrollDirection.Horizontal
collectionView?.bounces = false
collectionView?.pagingEnabled = true
collectionView?.showsHorizontalScrollIndicator = false
}
}
2. 創(chuàng)建控制器繼承自UICollectionViewController
private let reuseIdentifier = "Cell"
private let numberOfPages = 4
class FlowLayoutViewController: UICollectionViewController {
// 重寫(xiě)初始化方法, 初始化時(shí)必須指定布局
let layout: UICollectionViewFlowLayout = NewFeatureLayout()
init() {
super.init(collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// 注冊(cè)cell
self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
// MARK: UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfPages
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell
cell.imageIndex = indexPath.item
return cell
}
}
3. 自定義cell
class FlowLayoutCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
// add subView onto contentView
contentView.addSubview(imageView)
contentView.addSubview(startButton)
// set constraints for ImageView
imageView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(0)
make.bottom.equalTo(0)
make.leading.equalTo(0)
make.trailing.equalTo(0)
}
// set constraints for startButton
startButton.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(contentView)
make.bottom.equalTo(-150)
}
}
// set imageView's image when imageIndex was set
var imageIndex: Int? {
didSet{
imageView.image = UIImage(named: "new_feature_\(imageIndex! + 1)")
if imageIndex == 3 {
startButton.hidden = false
}
}
}
// lazy loading
private lazy var imageView = UIImageView()
private lazy var startButton: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "new_feature_button"), forState: .Normal)
button.setImage(UIImage(named: "new_feature_button_highlighted"), forState: .Highlighted)
button.addTarget(self, action: "enterWeiboClick", forControlEvents: .TouchUpInside)
button.hidden = true
return button
}()
// enterWeibo button click
func enterWeiboClick() {
print(__FUNCTION__)
}
}
-
方法調(diào)用順序
- collectionView(_:numberOfItemsInSection:) // 詢(xún)問(wèn)控制器要顯示的cell的個(gè)數(shù)
- prepareLayout() // 開(kāi)始布局
- collectionView(_:cellForItemAtIndexPath:) // 問(wèn)控制器要cell
- init(frame:) // 初始化cell