iOS下用一行代碼實現tableview(collectionview)的parallax效果

來源:互聯網
上載者:User

iOS下用一行代碼實現tableview(collectionview)的parallax效果

 

 

原理很簡單,就是一個等比公式

cell的圖片位置 / cell圖片可以滑動的總長 cell在table中的位置 / cell 可滑動總長

 

實現方法:

1》 在cell的UIImageView上添加父視圖UIView,clipsToBounds設定為yes,用來剪下UIImageView,為其限定大小。

 

2》在vc的

-(void)scrollViewDidScroll:(UIScrollView *)scrollView

中即時更新每個cell的圖片位置。

代碼如下

 

 

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{    for(WELTableViewCell * cell in [self.tableView visibleCells])    {        cell.image.frame = CGRectOffset(cell.image.frame, 0, ((cell.image.frame.size.height - cell.imageFrameView.frame.size.height) * ((cell.frame.origin.y + cell.imageFrameView.frame.size.height - self.tableView.contentOffset.y) / (self.tableView.frame.size.height + cell.imageFrameView.frame.size.height * 2)) + cell.imageFrameView.frame.size.height - cell.image.frame.size.height) - cell.image.frame.origin.y);    }}

PS:確實是一行代碼,哈哈。其實一行代碼只是一個噱頭,完全可以多寫幾行增加可讀性。之所以寫一行代碼,是想表達這個效果其實蠻簡單的。用算式算出位移量,重設frame。

 

 

3》在tableView初次重新整理完畢後,調用

[self scrollViewDidScroll:nil];

例如

 

-(void)viewDidAppear:(BOOL)animated

{

[super viewDidAppear:YES];

[self scrollViewDidScroll:nil];

}

 

最後,附上原始碼demo(發帖不易,討個積分,哈哈)

簡單demo(附註釋)

 

以上


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.