UITableView滑動視差

UITableView滑動視差orm

 

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

 

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

#pragma mark - UITablViewDataSourcestring

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{it

    return 1;io

}table

 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{scroll

    return [self.dataSource count];queue

}im

 

-(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;

}

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

#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

滑動視差調用方式:

-(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.height*OFFSET_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;

}

相關文章
相關標籤/搜索