Search code examples
iosobjective-cuiscrollviewuicollectionviewindicator

UIView that follows UICollectionView indicator


I want to create a custom UIView that contains a UIImageView and a UILabel, that points to the UICollectionView scroll indicator, and scrolls with it.

enter image description here

i am using this code :

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //get refrence of vertical indicator
    UIImageView *verticalIndicator = ((UIImageView *)[scrollView.subviews objectAtIndex:(scrollView.subviews.count-1)]);
    // get the relative position of the indicator in the main window
    CGPoint p = [verticalIndicator convertPoint:verticalIndicator.bounds.origin toView:[[UIApplication sharedApplication] keyWindow]];
    // set the custom view new position
    CGRect indicatorFrame = self.indicatorView.frame;
    indicatorFrame.origin.y = p.y;
    self.indicatorView.frame = indicatorFrame;
}

But the indicatorView does not follow the indicator exactly !!


Solution

  • This worked for me: Please look at the attached gif. I have added the custom uiview with blue color parallel to the scrool indicator.

    I tried for the table view, but this also works for the collection view too.

    enter image description here

    -(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
        dispatch_async(dispatch_get_main_queue(), ^{
            //get refrence of vertical indicator
            UIImageView *verticalIndicator = ((UIImageView *)[scrollView.subviews objectAtIndex:(scrollView.subviews.count-1)]);
            // get the relative position of the indicator in the main window
            //    CGPoint p = [verticalIndicator convertPoint:verticalIndicator.bounds.origin toView:[[UIApplication sharedApplication] keyWindow]];
    
            CGPoint p = CGPointMake(verticalIndicator.frame.origin.x-10,
                                    verticalIndicator.frame.origin.y - scrollView.contentOffset.y);
            // set the custom view new position
            CGRect indicatorFrame = CGRectMake(verticalIndicator.frame.origin.x, verticalIndicator.frame.origin.y, 10, 10);
             self.indicatorView.frame = indicatorFrame;
           });
    
      }
    

    Also maske sure you added the uiview in you view did load method.

    //in viewDidLoad:

    Note that I have used the sample values for the indicatorView postion.You can replace these as per your need.

    indicatorView=[[UIView alloc]initWithFrame:CGRectMake( p.x, p.y , 10, 10)];
    
    indicatorView.backgroundColor=[UIColor blueColor];
    
    [self.tableView addSubview:indicatorView];