iOS開發-UITableView滑動視差

ui594q8h 8年前發布 | 10K 次閱讀 Objective-C開發 UITableView

來自: http://www.cnblogs.com/xiaofeixiang/p/5152828.html

視差滾動是指讓多層背景以不同的速度移動,形成立體的運動效果,在Web上應用的比較多,App中倒是見的相對比較少,主要在UITableView中的應用的比較多,尤其是當整個UITableViewCell的背景是圖片的時候,描述內容較少,滑動視差可以增強視覺效果,可以考慮使用,先來簡單的看一下效果:

實現起來也比較簡單,UITableView定義:

#pragma mark - UITablViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return [self.dataSource count]; }

-(UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath )indexPath{ MainTableViewCell mainCell=[tableView dequeueReusableCellWithIdentifier:CELLIDENTIFIER forIndexPath:indexPath]; NSString *desc=[NSString stringWithFormat:@"FlyElephant-%ld",indexPath.row]; [mainCell setBackImage:self.dataSource[indexPath.row] description:desc]; return mainCell; }

pragma mark - UITableViewDelegate

-(CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath{ return 150; }</pre>

滑動的時候修改單元格偏移量:

#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint offset=self.tableView.contentOffset;
    for (MainTableViewCell *cell in self.tableView.visibleCells) {
        //方式1
//        [cell setImagOffset:offset tableView:self.tableView];
        //方式2
        [cell setAdjustOffset:(cell.frame.origin.y-offset.y)];
    }
}

MainTableViewCell定義:

@interface MainTableViewCell : UITableViewCell

-(void)setBackImage:(NSString )imageName description:(NSString )desc;

//視差滑動方式1 -(void)setImagOffset:(CGPoint)contentOffset tableView:(UITableView *)tablView;

//視差滑動方式2 -(void)setAdjustOffset:(CGFloat)offset;

@end</pre>

滑動視差調用方式:

-(void)setImagOffset:(CGPoint)contentOffset tableView:(UITableView )tablView{
    //偏移量
    CGFloat cellOffset = self.frame.origin.y - contentOffset.y;
    // 偏移量+單元格高度/tableview高度+單元格高度
    CGFloat percent = (cellOffset+self.frame.size.height)/(tablView.frame.size.height+self.frame.size.height);
    //偏移比例(0-1)
    CGFloat extraHeight = self.frame.size.heightOFFSET_RATE;

CGRect frame=self.backImageView.frame;
frame.origin.y=extraHeight*percent;
self.backImageView.frame=frame;

}

-(void)setAdjustOffset:(CGFloat)offset{ CGRect frame = self.backImageView.frame; frame.origin.y = (offset / 15.0); self.backImageView.frame = frame; }</pre>

實現起來比較簡單,網上有各種各樣的版本,這兩種的方式算是最簡單的實現~

</div>

 本文由用戶 ui594q8h 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!